失效原因
1.@SpringBootApplication启动类当中没有添加@EnableAsync注解。
2.异步方法使用注解@Async的返回值只能为void或者Future。
3.没有走Spring的代理类。因为@Transactional和@Async注解的实现都是基于Spring的AOP,而AOP的实现是基于动态代理模式实现的。那么注解失效的原因就很明显了,有可能因为调用方法的是对象本身而不是代理对象,因为没有经过Spring容器管理。
问题代码:
一个类中调用了本类的方法,没有走代理对象。
@PostConstruct
public void test(){
Long a = System.currentTimeMillis();
try {
test1();
test2();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(">>>>>>>"+(System.currentTimeMillis()-a));
}
@Async("")
public void test1() throws InterruptedException {
System.out.println(1);
Thread.sleep(10000);
System.out.println(2);
}
@Async("")
public void test2() throws InterruptedException {
System.out.println(3);
Thread.sleep(10000);
System.out.println(4);
}
执行结果就是
1->2->3->4
解决:
增加接口类和实现类
public interface DataService {
public void test1();
public void test2();
}
实现类:
@Service
public class DataServiceImpl implements DataService {
@Override
@Async("asyncServiceExecutor")
public void test1() {
System.out.println(1);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(2);
}
@Override
@Async("asyncServiceExecutor")
public void test2() {
System.out.println(3);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(4);
}
}
调用:
@Autowired
private DataService dataService;
@PostConstruct
public void test(){
Long a = System.currentTimeMillis();
dataService.test1();
dataService.test2();
System.out.println(">>>>>>>"+(System.currentTimeMillis()-a));
}
执行结果就是
1->3->2->4 或者1->3->4->2