Stage 7: microservice development | 01-springboot | 17 task [watch wild God's essays]

Task (asynchronous, scheduled, mail)

Asynchronous task~

  • Multithreading

Timed task~

  • timer
  • Expression~

Mail sending~

  • time
  • pop3/SMTP service

1, Asynchronous task (async)

1. Application scenario

​ 1. It takes time to send e-mail. Open asynchrony to let the user receive the information of the sent e-mail first, and then another thread sends it successfully after the waiting time of sending e-mail

2. Cases
  • Simulate a 3-second delay operation, and then delay the display of ok to the page. Now: to display ok, one thread will delay another thread by 3 seconds [if it is not added, the word ok will be loaded for 3 seconds before it comes out, affecting the user experience]
  1. Write the simulation code first

    • service Under the bag AsyncService
      
      @Service
      public class AsyncService {
      
      
          public void delay(){
              try {
                  Thread.sleep(3000);
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }
      
              System.out.println("Data processing...");
          }
      }
      
    • controller Under the bag AsyncController
      
      @RestController
      public class AsyncController {
      
          @Autowired
          AsyncService asyncService;
      
          /*
          * What we need to achieve is that one thread directly outputs ok and the other thread does the operation with a delay of 3 seconds [does not affect the user experience]
          * */
          @RequestMapping("/delay")
          public String delay(){
              //Calling this method will delay 3 seconds,
              asyncService.delay();
              return "ok";
          }
      }
      
  2. Tell Spring on the delay method that this is an asynchronous method

    • [@ Async notes]

    • With this annotation, as long as the program runs, it will open several thread pools for us

    • The asynchronous annotation function needs to be enabled in the main method

    • service Under the bag AsyncService
      
      @Service
      public class AsyncService {
      
      	//Tell Spring on the delay method that this is an asynchronous method
      	@Async
          public void delay(){
              try {
                  Thread.sleep(3000);
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }
      
              System.out.println("Data processing...");
          }
      }
      
  3. Once this annotation is added, it is necessary to * * [enable asynchronous annotation function] in the main method**

    • [@ EnableAsync annotation]

    • //Enable asynchronous annotation
      @EnableAsync
      @SpringBootApplication
      public class Springboot09AsyncApplication {
      
          public static void main(String[] args) {
              SpringApplication.run(Springboot09AsyncApplication.class, args);
          }
      
      }
      

2, Mail sending

1. Configure jar package
2. Send with qq here
  1. Find the account page of qq email and start the agreement service

  1. A password is generated instead of its own plaintext password

3. Configure application yaml
spring:
  mail:
    username: 834399035@qq.com
    #Configured dynamic password
    password: kcsigtxaclybbfdj
    #Configure sending server
    host: smtp.qq.com
    # Set ssl on
    properties:
      mail:
        stmp:
          ssl:
            enable: true
         
    ##The following are turned on as appropriate
    # The default protocol is smtp
    #protocol: smtp
    #default-encoding: utf-8
    #port: 465
    # qq mailbox needs Turn on mailbox verification
    #properties.mail.smtp.ssl.enable=true
    #port: 587
    
4. Write the Test of sending e-mail in the Test test [write it in the Test first, and then write it in the controller or service]
@SpringBootTest
class Springboot09AsyncApplicationTests {

    @Autowired
    JavaMailSenderImpl javaMailSender;

    @Test
    void contextLoads() {

        //A simple email
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        //title
        mailMessage.setSubject("Hello");
        //content
        mailMessage.setText("Your computer is suspected of stealing state secrets");
        mailMessage.setSentDate(new Date());
        //To whom
        mailMessage.setTo("496228526@qq.com");
        //From where
        mailMessage.setFrom("834399035@qq.com");

        javaMailSender.send(mailMessage);
    }

}
5. Write a complex email and send it [write it to Test first, and then write it to controller or service]
@Test
    void contextLoads2() throws MessagingException {

        //A complex mail sending
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //Assembly (you need to throw an exception here)
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

        //text
        helper.setSubject("Hello g1x");
        helper.setText("Send a complex email (with attachments)");

        //enclosure
        helper.addAttachment("2.jpg", new File("E:\\pictureOrFilms\\picture\\dota\\2.jpg"));
        helper.addAttachment("3.jpg", new File("E:\\pictureOrFilms\\picture\\dota\\3.jpg"));

        //send out
        helper.setFrom("834399035@qq.com");
        helper.setTo("834399035@qq.com");

        javaMailSender.send(mimeMessage);
    }

6. Write a tool class [that is, write a method]

    /**     *     * @param html  :The first parameter: whether to support multi text uploading, where true is changed to HTML * @ param subject: Title * @ param text: body * @ throws messagingexception * @ author G1x: see your needs by analogy later     */    public void sendMail(Boolean html, String subject, String text) throws MessagingException {        //Send a complex message mimemessage mimemessage = javamailsender createMimeMessage();        // Assembly (exceptions need to be thrown here) MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, html)// Text helper setSubject(subject);         helper. setText(text);        // Attachment helper addAttachment("2.jpg", new File("E:\pictureOrFilms\picture\dota\2.jpg"));         helper. addAttachment("3.jpg", new File("E:\pictureOrFilms\picture\dota\3.jpg"));        // Send helper setFrom(" 834399035@qq.com ");        helper.setTo(" 834399035@qq.com ");        javaMailSender.send(mimeMessage);    }

3, Timed task

*Two core interfaces
TaskScheduler	//Task scheduler TaskExecutor 	// Task executor
1. Notes to be added on the main operation method
@EnableScheduling	//Enable timed annotation function @ Scheduled 	// When to execute ------------------- / / enable asynchronous annotation@ EnableAsync@SpringBootApplication //Enable the timed annotation function @ enablesschedulingpublic class springboot09asyncapplication {public static void main (string [] args) {springapplication.run (springboot09asyncapplication. Class, args);}}
3. cron expression used in @ scheduled
  • This cron expression can be generated online: https://cron.qqe2.com/

  • There are also many examples of cron expressions: https://www.cnblogs.com/yanghj010/p/10875151.html

  • //The Service layer writes @ servicepublic class scheduledservice {/ / cron expression / / seconds, minutes, hours, days, months and weeks / / the following represents all @ scheduled (cron = "0 35 17 * *?") Public void hello() {system. Out. Println ("Hello, you are executed!");}}
    
4. Summary: big data development is often used

Keywords: Java Spring Boot

Added by daijames on Tue, 18 Jan 2022 01:33:53 +0200