背景
开发时发现,同一个接口方法对获取的数据需要入库,之后再返回,结构复杂的话,解析入库的过程非常耗时间,所以开启一个异步线程去执行入库任务。
关键注解
@EnableAsync:启用 Spring 异步方法执行功能
@Async:异步方法
启动类需添加@EnableAsync开启对异步的支持
public static int[] num = null;
//模拟耗时
@Async
public void startThread(){
try{
synchronized (num){
for (int a:num) {
Thread.sleep(1000);
System.err.println(a);
}
}
}catch (Exception e){}
}
public void test(){
System.err.println(Thread.currentThread().getName());
ThreadStart.num = new int[]{0,1,2};
start.startThread();
System.err.println("执行完成,客户端返回结果");
}
实现
正常同步执行顺序
添加@Async之后执行(发现执行顺序已经发生变化)
@Async失效的场景
- 异步方法使用static修饰
- 异步类没有使用@Component注解(或其他注解)导致spring无法扫描到异步类
- 异步方法不能与异步方法在同一个类中
- 类中需要使用@Autowired或@Resource等注解自动注入,不能自己手动new对象
- 使用@Async时不能有返回值