springboot 与任务

时间:2023-03-10 01:51:42
springboot 与任务

异步任务、定时任务、邮件任务

一、异步任务

在Java应用中,绝大多数情况下都是通过同步的方式来实现交互处理的;但是在
处理与第三方系统交互的时候,容易造成响应迟缓的情况,之前大部分都是使用
多线程来完成此类任务,其实,在Spring 3.x之后,就已经内置了@Async来完
美解决这个问题。

两个注解: @EnableAysnc、@Aysnc

@EnableAsync
@SpringBootApplication
public class Springboot04TaskApplication { public static void main(String[] args) {
SpringApplication.run(Springboot04TaskApplication.class, args);
} }
RestController
public class AysncController {
@Autowired
AsyncService asyncService; @GetMapping("/hello")
public String hello(){
asyncService.hello();
return "success";
}
}
@Service
public class AsyncService { // 告诉spring 这是一个异步方法
@Async
public void hello(){
try{
Thread.sleep(3000);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println("数据处理中...");
}
}

二、定时任务

项目开发中经常需要执行一些定时任务,比如需要在每天凌晨时候,分析一次前
一天的日志信息。Spring为我们提供了异步执行任务调度的方式,提供
TaskExecutor 、TaskScheduler 接口。
两个注解:@EnableScheduling、@Scheduled

springboot 与任务

springboot 与任务

springboot 与任务

三、邮件任务

• 邮件发送需要引入spring-boot-starter-mail
• Spring Boot 自动配置MailSenderAutoConfiguration
• 定义MailProperties内容,配置在application.yml中
• 自动装配JavaMailSender
• 测试邮件发送

springboot 与任务

springboot 与任务

springboot 与任务

springboot 与任务