在Java应用中,绝大多数情况下都是通过同步的方式来实现交互处理的;但是在处理与第三方系统交互的时候,容易造成响应迟缓的情况,之前大部分都是使用多线程来完成此类任务,其实,在Spring 3.x之后,就已经内置了@Async来完美解决这个问题。
1.启动器上添加 @EnableAsync 注解
@EnableScheduling //开启注解的定时任务
@SpringBootApplication
public class Springboot04TaskApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot04TaskApplication.class, args);
}
}
2.service 添加注解
@Service
public class AsyncService {
//告诉Spring这是一个异步任务
@Async
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("处理数据中...");
}
}
3.controller
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@GetMapping("/hello")
public String hello(){
asyncService.hello();
return "Success";
}
}
访问效果:
若果没有开启异步,访问 /hello 3秒后,控制台打印 “处理数据中...”以及返回 “Success”。 开启后:访问 /hello 直接返回 “Success”,3秒后控制台打印返回 “Success”。
二、定时任务
1.启动器上添加 @EnableScheduling 注解
2.需要执行的方法添加 @Scheduled(cron="")
@Service
public class ScheduledService {
/**
* second(秒) , minute(分 ), hour(时), day of month(日), month(月) ,day of week(周几 ).
*
* 0 * * * * MON-FRI
* 周一到周五,每月,每日,每时,每分,整秒启动一次 (周一到周五每分钟启动 一次)
* * * * * * MON-FRI 周一到周五每秒启动一次
*
* 例子:
*
* 【0 0/5 14,18 * * ?】 每天14点整,和18点整,每隔5分钟执行一次
* 【0 15 10 ? * 1-6】 每个月的周一至周六10:15分执行一次
* 【0 0 2 ? * 6L】每个月的最后一个周六凌晨2点执行一次
* 【0 0 2 LW * ?】每个月的最后一个工作日凌晨2点执行一次
* 【0 0 2-4 ? * 1#1】每个月的第一个周一凌晨2点到4点期间,每个整点都执行一次;
*/
// @Scheduled(cron = "0 * * * * SUN-SAT")
// @Scheduled(cron = "0,1,2,3,4 * * * * SUN-SAT") // 枚举 0,1,2,3,4这些秒会运行
// @Scheduled(cron = "0-4 * * * * SUN-SAT") // 区间 0-4 秒都会运行
@Scheduled(cron = "0/4 * * * * SUN-SAT") // 步长 每隔4秒启动一次
public void hello(){
System.out.println("hello service ......");
}
}
cron表达式
