SpringBoot integrates asynchronous, timing, and mail tasks

Asynchronous task

1. Create a service package

2. Create a class AsyncService

Asynchronous processing is still very common. For example, when we send emails on the website, the background will send emails. At this time, the front desk will cause the response to be inactive. The response will not succeed until the email is sent, so we generally use multi-threaded methods. Deal with these tasks.

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

@Service
public class AsyncService {
    
    

   public void hello(){
    
    
       try {
    
    
           Thread.sleep(3000);
      } catch (InterruptedException e) {
    
    
           e.printStackTrace();
      }
       System.out.println("业务进行中....");
  }
}

3. Write the controller package

4. Write the AsyncController class

Let's write a Controller to test

@RestController
public class AsyncController {
    
    

   @Autowired
   AsyncService asyncService;

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

}

5. Visit http://localhost:8080/hello to test, and success appears after 3 seconds, which is a synchronous waiting situation.

Question: If we want the user to get the message directly, we can use multi-threaded processing in the background, but every time we need to manually write the multi-threaded implementation, it is too troublesome, we only need to use a simple The way is to add a simple annotation to our method, as follows:

6. Add @Async annotation to the hello method;

//告诉Spring这是一个异步方法
@Async
public void hello(){
    
    
   try {
    
    
       Thread.sleep(3000);
  } catch (InterruptedException e) {
    
    
       e.printStackTrace();
  }
   System.out.println("业务进行中....");
}

SpringBoot will open a thread pool by itself and make calls! But for this annotation to take effect, we also need to add an annotation @EnableAsync to the main program to enable the asynchronous annotation function;

@EnableAsync //开启异步注解功能
@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!

Timed task

In project development, we often need to perform some timed 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 perform task scheduling asynchronously and provides two interfaces.

TaskExecutor接口

TaskScheduler接口

Two notes:

@EnableScheduling

@Scheduled

cron expression:

Insert picture description here

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 {
    
    
   
   //秒   分   时     日   月   周几
   //0 * * * * MON-FRI
   //注意cron表达式的用法;
   @Scheduled(cron = "0 * * * * 0-7")
   public void hello(){
    
    
       System.out.println("hello.....");
  }
}

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

@EnableAsync //开启异步注解功能
@EnableScheduling //开启基于注解的定时任务
@SpringBootApplication
public class SpringbootTaskApplication {
    
    

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

}

3. Let's learn more about cron expressions;

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

4. Commonly used expressions

10/2 * * * * ?   表示每2秒 执行任务
(10 0/2 * * * ?   表示每2分钟 执行任务
(10 0 2 1 * ?   表示在每月的1日的凌晨2点调整任务
(20 15 10 ? * MON-FRI   表示周一到周五每天上午10:15执行作业
(30 15 10 ? 6L 2002-2006   表示2002-2006年的每个月的最后一个星期五上午10:15执行作
(40 0 10,14,16 * * ?   每天上午10点,下午2点,4点
(50 0/30 9-17 * * ?   朝九晚五工作时间内每半小时
(60 0 12 ? * WED   表示每个星期三中午12点
(70 0 12 * * ?   每天中午12点触发
(80 15 10 ? * *   每天上午10:15触发
(90 15 10 * * ?     每天上午10:15触发
(100 15 10 * * ?   每天上午10:15触发
(110 15 10 * * ? 2005   2005年的每天上午10:15触发
(120 * 14 * * ?     在每天下午2点到下午2:59期间的每1分钟触发
(130 0/5 14 * * ?   在每天下午2点到下午2:55期间的每5分钟触发
(140 0/5 14,18 * * ?     在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发
(150 0-5 14 * * ?   在每天下午2点到下午2:05期间的每1分钟触发
(160 10,44 14 ? 3 WED   每年三月的星期三的下午2:102:44触发
(170 15 10 ? * MON-FRI   周一至周五的上午10:15触发
(180 15 10 15 * ?   每月15日上午10:15触发
(190 15 10 L * ?   每月最后一日的上午10:15触发
(200 15 10 ? * 6L   每月的最后一个星期五上午10:15触发
(210 15 10 ? * 6L 2002-2005   2002年至2005年的每月的最后一个星期五上午10:15触发
(220 15 10 ? * 6#3   每月的第三个星期五上午10:15触发

Mail task

There are a lot of emails sent in our daily development, and Springboot also helped us to support

Email sending needs to introduce spring-boot-start-mail

SpringBoot automatically configures MailSenderAutoConfiguration

Define the content of MailProperties and configure it in application.yml

Automatic assembly of JavaMailSender

Test mail sending

test:

1. Introduce pom dependency

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

Look 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 the automatic configuration class: MailSenderAutoConfiguration

There is a bean in this class, JavaMailSenderImpl

Then we go to 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. Configuration file:

[email protected]
spring.mail.password=你的qq授权码
spring.mail.host=smtp.qq.com

QQ needs to configure ssl

spring.mail.properties.mail.smtp.ssl.enable=true to
obtain the authorization code: Settings in the QQ mailbox -> account -> open pop3 and smtp services

4. Spring unit testing

@Autowired
JavaMailSenderImpl mailSender;

@Test
public void contextLoads() {
    
    
   //邮件设置1:一个简单的邮件
   SimpleMailMessage message = new SimpleMailMessage();
   message.setSubject("通知-明天来狂神这听课");
   message.setText("今晚7:30开会");

   message.setTo("[email protected]");
   message.setFrom("[email protected]");
   mailSender.send(message);
}

@Test
public void contextLoads2() throws MessagingException {
    
    
   //邮件设置2:一个复杂的邮件
   MimeMessage mimeMessage = mailSender.createMimeMessage();
   MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

   helper.setSubject("通知-明天来狂神这听课");
   helper.setText("<b style='color:red'>今天 7:30来开会</b>",true);

   //发送附件
   helper.addAttachment("1.jpg",new File(""));
   helper.addAttachment("2.jpg",new File(""));

   helper.setTo("[email protected]");
   helper.setFrom("[email protected]");

   mailSender.send(mimeMessage);
}

Check the mailbox, the mail is received successfully!

We only need to use Thymeleaf for front-end and back-end integration to develop our own website mail sending and receiving functions!

Guess you like

Origin blog.csdn.net/david2000999/article/details/115253339