异步调用无需等待,方法相当于子线程,后台执行,主线程执行完成,子线程开始执行。
SpringBoot 开启异步执行仅需两步:
方法上加 @Async
- @Override
- @Async
- @Transactional(rollbackFor = Exception.class)
- public Integer init(DatePojo datePojo){
- //xxxxxxxxxxx 业务略 xxxxxxx
- log.info(" 起止日期为 : {},{} ",start,end);
- //xxxxxxxxxxxxx 业务略 xxxxxxx
- log.info(" ------------------ 【能源入库完成】------------------ {}",nyList);
- log.info(" ------------------ 【新能源初始化结束】------------------");
- return 0;
- }
main 方法 开启 @EnableAsync
- @SpringBootApplication
- @EnableAsync
- public class Application {
- public static void main(String[] args) {
- SpringApplication.run(Application.class,args);
- }
- }
controller
执行结果
可以看到 controller 先执行完成然后返回状态,接着 方法才开始执行。
Spring之AOP奇葩报错:Null return value from advice does not match primitive return type for
原因是返回为null 基本类型要用包装类型。
总结
1 使用了@Async的方法,会被当成是一个子线程,所有整个sendSms方法,会在主线程执行完了之后执行