在springboot中开启异步任务十分简单只需要两步
在主启动类中添加注解
@EnableAsync
1
2
3
4
5
6
7
8
// 开启异步注解功能
public class Springboot08TestApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot08TestApplication.class, args);
}
}在服务中使用注解
@Async
表示该任务为异步1
2
3
4
5
6
7
8
9
10
11
12
13
public class AsyncService {
// 告诉spring这是异步的方法
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("doing");
}
}
这样的话,在controller中,程序遇见异步服务将直接执行下一步
1 |
|
结果是ok将会先行返回,三秒后doing才会被打印