在我们开发项目时,常常会用到异步处理任务,比如我们在网站上发送邮件,后台会去发送邮件,此时会造成前台响应不动,直到邮件发送完毕,响应才会成功,所以我们一般会采用多线程的方式去处理这些任务。
1. 新建一个service包
2. 创建AsyncService类
@Service
public class AsyncService {
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("业务进行中~~");
}
}
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@GetMapping("/hello")
public String hello(){//调用方法后会延迟3秒在页面显示Success
asyncService.hello();
return "success";
}
}
此时访问Localhost:8080/hello的情况是:延迟3秒后,在页面输出Success,在后台会输出业务进行中~~
@Async//告诉Spring这是一个异步方法
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("业务进行中~~");
}
但是要让这个注解起作用,还需要在入口文件中开启异步注解功能
@EnableAsync //开启异步注解功能
@SpringBootApplication
public class SpringbootTaskApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootTaskApplication.class, args);
}
}
此时再次测试,发现页面直接输出了Success,但是后台仍然是3秒后输出业务进行中
工作中常常要设置一些定时任务,比如每天在某个时间分析一遍日志
所以Spring提供了异步执行任务调度的方式,提供了两个接口。
TaskExecutor接口
TaskScheduler接口
两个注解:
• @EnableScheduling
• @Scheduled
@Service
publicclassScheduledService{
//秒分时日月周几
@Scheduled(cron="0 * * * * ?")
//这里需要学习一些cron表达式的语法,明白时间如何设置,这里的意思是每当时间到0秒时就执行一次
publicvoidhello(){
System.out.println("hello/////");
}
}
2.要使用定时功能,还需要在入口文件中加上@EnableScheduling,表明开启定时任务功能
@SpringBootApplication
@EnableScheduling//开启定时任务注解功能
@EnableAsync//开启异步注解功能
publicclassSpringbootTaskApplication{
publicstaticvoidmain(String[]args){
SpringApplication.run(SpringbootTaskApplication.class,args);
}
}
此时测试运行,发现每当时间为0秒时就会在后台打印出 hello////
本文地址:https://blog.csdn.net/L_GRAND_ORDER/article/details/107599690
如对本文有疑问, 点击进行留言回复!!
浅谈Java如何实现一个基于LRU时间复杂度为O(1)的缓存
JDK1.6“新“特性Instrumentation之JavaAgent(推荐)
before社区电量是什么意思 Before社区电量获得方法
网友评论