1. SpringBoot–异步任务
在Java应用中,绝大多数情况下都是通过同步的方式来实现交互处理的;但是在处理与第三方系统交互的时候,容易造成响应迟缓的情况,之前大部分都是使用多线程来完成此类任务,其实,在Spring 3.x之后,就已经内置了@Async来完美解决这个问题。
两个注解:
@EnableAysnc:开启异步注解功能
@Aysnc:异步注解
在Spring中,基于@Async标注的方法,称之为异步方法;这些方法将在执行的时候,将会在独立的线程中被执行,调用者无需等待它的完成,即可继续其他的操作。
1、在Service层写一个异步方法:
@Async标注方法
@Service
public class AsyncService {
/**
* 在Spring中,基于@Async标注的方法,称之为异步方法;
* 这些方法将在执行的时候,将会在独立的线程中被执行,调用者无需等待它的完成,即可继续其他的操作。
*/
@Async
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("处理数据中...");
}
}
2、在Controller层调用Service层的方法:
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@GetMapping("/hello")
public String hello(){
/**
* 同步方法,需要先等待asyncService.hello()方法执行结束,才能继续向下执行 return "success";
* 异步方法,不需要等待asyncService.hello()方法执行结束,即可执行return "success";
*/
asyncService.hello();
return "success";
}
}
3、使用 @Async注解一定要开启异步注解功能,否则注解无效
主配置类上开启@EnableAsync
//开启异步注解功能
@EnableAsync
@SpringBootApplication
public class SpringbootTaskApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootTaskApplication.class, args);
}
}
2、SpringBoot --定时任务
项目开发中经常需要执行一些定时任务,比如需要在每天凌晨时候,分析一次前一天的日志信息。 Spring为我们提供了异步执行任务调度的方式,提供TaskExecutor 、TaskScheduler 接口。
两个注解: @EnableScheduling:开启基于注解的定时任务 @Scheduled:定时任务
cron表达式:
定时任务,就是按照预定的时间去执行一些任务:
1、写一个定时任务,每周一到周六整分的时候在控制台打印hello
@Service
public class ScheduledService {
/**
* second(秒), minute(分), hour(时), day (日), month(月), week(周几).
* 1、0 * * * * MON-FRI
* 0:0秒的时候(整分的时候)
* *:每一分钟
* *:每一小时
* *:每一天
* *:每一月
* MON-FRI:周1到周五
*
* 2、0 0/5 14,18 * * ? :每天14点整,和18点整,每隔5分钟执行一次
* 3、0 15 10 ? * 1-6 :每个月的周一至周六10:15分执行一次
* 4、0 0 2 ? * 6L :每个月的最后一个周六凌晨2点执行一次
* 5、0 0 2 LW * ? :每个月的最后一个周六凌晨2点执行一次
* 6、0 0 2-4 ? * 1#1 :每个月的第一个周一凌晨2点到4点期间,每个整点都执行一次;
*
* @Scheduled(cron = "0,1,2,3,4 * * * * MON-SAT")
* @Scheduled(cron = "0-4 * * * * MON-SAT")
* @Scheduled(cron = "0/4 * * * * MON-SAT") //每4秒执行一次
*/
@Scheduled(cron = "0 * * * * MON-SAT")
public void hello(){
System.out.println("hello ... ");
}
}
2、使用 @Scheduled(cron = “0 * * * * MON-SAT”)注解,必须开启定时任务注解功能@SpringBootApplication
//开启基于注解的定时任务
@EnableScheduling
@SpringBootApplication
public class SpringbootTaskApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootTaskApplication.class, args);
}
}