SpringBoot: asynchronous, scheduled, mail tasks

SpringBoot: asynchronous, scheduled, mail tasks

preface

In our work, we often use asynchronous processing tasks. For example, when we send mail on the website, the background will send mail. At this time, the foreground will cause the response to remain motionless. The response will not succeed until the mail is sent. Therefore, we generally use multithreading to process these tasks. There are also some scheduled tasks. For example, it is necessary to analyze the log information of the previous day in the early morning of each day. There is also e-mail sending. The predecessor of wechat is also e-mail service? How do these things come true? In fact, SpringBoot provides us with corresponding support. It's very easy for us to use. We just need to open some annotation support and configure some configuration files! Let's have a look~

Last edited on March 26, 2020 Author: Crazy God Theory

15.1 asynchronous tasks

1. Create a service package

2. Create an AsyncService class

Asynchronous processing is still very common. For example, when we send mail on the website, the background will send mail. At this time, the foreground will cause the response to remain motionless. The response will not succeed until the mail is sent. Therefore, we generally use multithreading to process these tasks.

Write a method to pretend to be processing data, use threads to set some delays, and simulate synchronous waiting;

@Service
public class AsyncService {

   public void hello(){
       try {
           Thread.sleep(3000);
      } catch (InterruptedException e) {
           e.printStackTrace();
      }
       System.out.println("Business in progress....");
  }
}

3. Write controller package

4. Writing the AsyncController class

Let's write a Controller and test it

@RestController
public class AsyncController {

   @Autowired
   AsyncService asyncService;

   @GetMapping("/hello")
   public String hello(){
       asyncService.hello();
       return "success";
  }

}

5. Visit http://localhost:8080/hello After the test, success appears after 3 seconds, which is the condition of synchronous waiting.

Problem: if we want users to get messages directly, we can use multithreading in the background, but it's too troublesome to manually write the multithreading implementation every time. We just need to use a simple method and add a simple annotation to our method, as follows:

6. Add @ Async annotation to hello method;

//Tell Spring that this is an asynchronous method
@Async
public void hello(){
   try {
       Thread.sleep(3000);
  } catch (InterruptedException e) {
       e.printStackTrace();
  }
   System.out.println("Business in progress....");
}

SpringBoot will open a thread pool and call it! However, to make this annotation effective, we also need to add an annotation @ EnableAsync on the main program to enable the asynchronous annotation function;

@EnableAsync //Enable asynchronous annotation
@SpringBootApplication
public class SpringbootTaskApplication {

   public static void main(String[] args) {
       SpringApplication.run(SpringbootTaskApplication.class, args);
  }

}

7. Restart the test, the web page responds instantly, and the background code is still executed!

15.2 scheduled tasks

During project development, we often need to perform some scheduled tasks. For example, we need to analyze the log information of the previous day in the early morning of each day. Spring provides us with a way to schedule tasks asynchronously and provides two interfaces.

  • TaskExecutor interface
  • TaskScheduler interface

Two notes:

  • @EnableScheduling
  • @Scheduled

cron expression:

[the external chain picture transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (IMG ivgndwua-1625824913368) (springboot: asynchronous, timed and mail tasks. Assets / 1905053-2020041225641164-1934062088. PNG)]

[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-xzSMB91h-1625824913370)(SpringBoot: asynchronous, timed and email tasks. Assets / 1905053-2020041225651289-251704533. PNG)]

Test steps:

1. Create a ScheduledService

There is a hello method in us. It needs to be executed regularly. How to deal with it?

@Service
public class ScheduledService {
   
   //Second minute hour day month week
   //0 * * * * MON-FRI
   //Pay attention to the usage of cron expression;
   @Scheduled(cron = "0 * * * * 0-7")
   public void hello(){
       System.out.println("hello.....");
  }
}

2. After writing the scheduled task here, we need to add @ enableshcheduling to the main program to enable the scheduled task function

@EnableAsync //Enable asynchronous annotation
@EnableScheduling //Enable annotation based scheduled tasks
@SpringBootApplication
public class SpringbootTaskApplication {

   public static void main(String[] args) {
       SpringApplication.run(SpringbootTaskApplication.class, args);
  }

}

3. Let's learn more about the cron expression;

http://www.bejson.com/othertools/cron/

4. Common expressions

 (1)0/2 * * * * ?   Indicates that the task is executed every 2 seconds
(1)0 0/2 * * * ?   Indicates that the task is executed every 2 minutes
(1)0 0 2 1 * ?   Indicates that the task is adjusted at 2 a.m. on the 1st of each month
(2)0 15 10 ? * MON-FRI   It means 10 a.m. every day from Monday to Friday:15 Execute job
(3)0 15 10 ? 6L 2002-2006   Indicates 2002-2006 10 a.m. on the last Friday of each month in:15 Executive work
(4)0 0 10,14,16 * * ?   Every day at 10 a.m., 2 p.m. and 4 p.m
(5)0 0/30 9-17 * * ?   Every half an hour during nine to five working hours
(6)0 0 12 ? * WED   It means 12 noon every Wednesday
(7)0 0 12 * * ?   Triggered at 12 noon every day
(8)0 15 10 ? * *   10 a.m. every day:15 trigger
(9)0 15 10 * * ?     10 a.m. every day:15 trigger
(10)0 15 10 * * ?   10 a.m. every day:15 trigger
(11)0 15 10 * * ? 2005   2005 10 a.m. every day in:15 trigger
(12)0 * 14 * * ?     Every day from 2 p.m. to 2 p.m:59 Triggered every 1 minute during
(13)0 0/5 14 * * ?   Every day from 2 p.m. to 2 p.m:55 Triggered every 5 minutes during
(14)0 0/5 14,18 * * ?     Every day from 2 p.m. to 2 p.m:55 During and from 6 p.m. to 6 p.m:55 Triggered every 5 minutes during
(15)0 0-5 14 * * ?   Every day from 2 p.m. to 2 p.m:05 Triggered every 1 minute during
(16)0 10,44 14 ? 3 WED   Every Wednesday in March at 2 p.m:10 And 2:44 trigger
(17)0 15 10 ? * MON-FRI   Monday to Friday at 10 a.m:15 trigger
(18)0 15 10 15 * ?   10 a.m. on the 15th of each month:15 trigger
(19)0 15 10 L * ?   10 a.m. on the last day of each month:15 trigger
(20)0 15 10 ? * 6L   10 a.m. on the last Friday of each month:15 trigger
(21)0 15 10 ? * 6L 2002-2005   2002 10 a.m. on the last Friday of each month from 2005 to 2005:15 trigger
(22)0 15 10 ? * 6#3 triggered at 10:15 a.m. on the third Friday of each month

15.3 mail task

Mail sending is also very much in our daily development, and Springboot also supports us

  • Spring boot start mail needs to be introduced for mail sending
  • SpringBoot auto configuration MailSenderAutoConfiguration
  • Define the MailProperties content and configure it in application In YML
  • Auto assemble JavaMailSender
  • Test mail sending

Test:

1. Introducing pom dependency

<<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

Looking at the dependencies it introduces, you can see Jakarta mail

<dependency>
   <groupId>com.sun.mail</groupId>
   <artifactId>jakarta.mail</artifactId>
   <version>1.6.4</version>
   <scope>compile</scope>
</dependency>

2. View autoconfiguration class: MailSenderAutoConfiguration

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-rpsYAfSq-1625824913372)(SpringBoot: asynchronous, timed and mail tasks. Assets / 1905053-2020041225708744-252995174. PNG)]

There are bean s in this class, JavaMailSenderImpl

[the external chain picture transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-TUDQo7oB-1625824913373)(SpringBoot: asynchronous, timed and mail tasks. assets/1905053-20200412225721465-1009548816.png)]

Then let's look at the configuration file

@ConfigurationProperties(
   prefix = "spring.mail"
)
public class MailProperties {
   private static final Charset DEFAULT_CHARSET;
   private String host;
   private Integer port;
   private String username;
   private String password;
   private String protocol = "smtp";
   private Charset defaultEncoding;
   private Map<String, String> properties;
   private String jndiName;
}

3. Profile:

spring.mail.username=24736743@qq.comspring.mail.password=Yours qq Authorization code spring.mail.host=smtp.qq.com# qq needs to configure sslspring mail. properties. mail. smtp. ssl. enable=true

Get authorization code: set in QQ email - > account - > start pop3 and smtp services

[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-1MaHLN7f-1625824913377)(SpringBoot: asynchronous, timed and mail tasks. Assets / 1905053-2020041225736355-1251829128. PNG)]

4. Spring unit test

@Autowired
JavaMailSenderImpl mailSender;

@Test
public void contextLoads() {
   //Mail setting 1: a simple mail
   SimpleMailMessage message = new SimpleMailMessage();
   message.setSubject("notice-Come to crazy God's class tomorrow");
   message.setText("Tonight 7:30 attend a meeting");

   message.setTo("24736743@qq.com");
   message.setFrom("24736743@qq.com");
   mailSender.send(message);
}

@Test
public void contextLoads2() throws MessagingException {
   //Mail setup 2: a complex mail
   MimeMessage mimeMessage = mailSender.createMimeMessage();
   MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

   helper.setSubject("notice-Come to crazy God's class tomorrow");
   helper.setText("<b style='color:red'>Today 7:30 Come to the meeting</b>",true);

   //Send attachments
   helper.addAttachment("1.jpg",new File(""));
   helper.addAttachment("2.jpg",new File(""));

   helper.setTo("24736743@qq.com");
   helper.setFrom("24736743@qq.com");

   mailSender.send(mimeMessage);
}

Check the mailbox and the mail is received successfully!

We only need to use Thymeleaf for front-end and back-end combination to develop our website mail sending and receiving function!

Keywords: Spring Boot

Added by l053r on Sun, 23 Jan 2022 01:07:43 +0200