EnableAsync注解的意思是可以异步执行,就是开启多线程的意思。可以标注在方法、类上。

@EnableAsync使用 随笔 第1张
 1 @Component
 2 public class Task {
 3 
 4     @Async
 5     public void doTaskOne() throws Exception {
 6         // 同上内容,省略
 7     }
 8 
 9     @Async
10     public void doTaskTwo() throws Exception {
11         // 同上内容,省略
12     }
13 
14     @Async
15     public void doTaskThree() throws Exception {
16         // 同上内容,省略
17     }
18 
19 }
@EnableAsync使用 随笔 第2张

为了让@Async注解能够生效,还需要在Spring Boot的主程序中配置@EnableAsync,如下所示:

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。 @EnableAsync使用 随笔 第3张
1 @SpringBootApplication
2 @EnableAsync
3 public class Application {
4 
5     public static void main(String[] args) {
6         SpringApplication.run(Application.class, args);
7     }
8 
9 }
@EnableAsync使用 随笔 第4张

注: @Async所修饰的函数不要定义为static类型,这样异步调用不会生效

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄