Asynchronous tasks, emails and timing tasks in SpringBoot

Asynchronous task

background

In our business processing, for example, it takes 3s to complete the processing, but if we need to let the user wait 3s, the experience is very poor, so we use an asynchronous method to process it, which can be processed through the thread pool, but we have to write Thread, and springboot has provided this ability by default, we just need to enable it to use.

Specific use

  • Create project

We only need to create a basic springboot project, and then just add web dependencies.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
  • Write the scene to simulate the above background

service layer:

@Service
public class AsyncService {

    public void sync(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("方法中在执行中");
    }

    public void async(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("方法中在执行中");
    }
}

Controller layer:

@RestController
public class AsyncController {

    @Autowired
    private AsyncService asyncService;

    @GetMapping("/sync")
    public String sync(){
        asyncService.sync();

        return "处理完成";
    }

    @GetMapping("/async")
    public String async(){
        asyncService.async();

        return "处理完成";
    }

}
  • Start project, test

Request localhost:8080/sync and find that it will turn around and wait for 3s before returning a value:

Asynchronous tasks, emails and timing tasks in SpringBoot

  • problem solved

Use asynchronous methods to solve this problem.

First turn on asynchronous on the startup class: @EnableAsync, and then add annotation @Async on the method to be called

# 启动类
 @SpringBootApplication
@EnableAsync
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}
#方法
    @Async
    public void async(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("方法中在执行中");
    }

Then I requested ocalhost:8080/async again, and found that our method returned immediately. This is the realization of asynchronous tasks.

Mail task

background

The mail task is realized through the mail-starter provided by springboot.

Specific use

  • Add dependency
<!--mail-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
  • Configuration file
[email protected]
spring.mail.password=你的qq授权码
spring.mail.host=smtp.qq.com
# qq需要配置ssl
spring.mail.properties.mail.smtp.ssl.enable=true

Obtain the authorization code: in the QQ mailbox settings -> account -> open pop3 and smtp services.

  • 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);

Timed task

background

Execute some code at a specified time or scene.

Associated classes and annotations

TaskScheduler  : 任务调度者
TaskExecutor   :任务执行者
@EnableScheduling  : 开启定时功能的注解
@schedule       :什么时候执行

Specific use

As long as the web dependency of springboot is imported, this function is imported for us by default, and we don't need to import it again.

For cron expressions, please refer to my other article: The use of @schedule annotation in spring

  • Add annotation @EnableScheduling to the startup class
@SpringBootApplication
@EnableAsync
@EnableScheduling
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}
  • Service layer writing method
@Service
public class ScheduleService {

    public void testSchedule(){
        System.out.println("任务被执行了");
    }
}
  • Add comment @Scheduled

The cron expression can refer to another blog of mine: the use of @schedule annotation in spring, which is to execute in a fixed time period

@Service
public class ScheduleService {

    /**
     * 每隔10s执行一次
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void testSchedule(){
        System.out.println(LocalDateTime.now()+"任务被执行了");
    }
}
  • result

Performed every 10s to verify the accuracy.

Asynchronous tasks, emails and timing tasks in SpringBoot

Guess you like

Origin blog.csdn.net/doubututou/article/details/112765499