SpringBoot开启异步调用方法

前端之家收集整理的这篇文章主要介绍了SpringBoot开启异步调用方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

异步调用无需等待,方法相当于子线程,后台执行,主线程执行完成,子线程开始执行。
SpringBoot 开启异步执行仅需两步:

方法上加 @Async

  1. @Override
  2. @Async
  3. @Transactional(rollbackFor = Exception.class)
  4. public Integer init(DatePojo datePojo){
  5.  
  6. //xxxxxxxxxxx 业务略 xxxxxxx
  7. log.info(" 起止日期为 : {},{} ",start,end);
  8.  
  9. //xxxxxxxxxxxxx 业务略 xxxxxxx
  10.  
  11. log.info(" ------------------ 【能源入库完成】------------------ {}",nyList);
  12. log.info(" ------------------ 【新能源初始化结束】------------------");
  13.  
  14. return 0;
  15.  
  16. }

main 方法 开启 @EnableAsync

  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. }

controller

  1. @PostMapping("/ny")
  2. public ReturnMessage ny( @RequestBody DatePojo datePojo,BindingResult result) {
  3. log.info(" 【 能源初始化接口调用开始 】");
  4. //业务类
  5. Integer data = xstjJdcNyService.init(datePojo);
  6. log.info(" 【 能源初始化接口调用结束 】");
  7.  
  8. return new ReturnMessage(CodeMsgEnum.OK.getCode(),CodeMsgEnum.OK.getMsg(),data);
  9. }

执行结果

SpringBoot开启异步调用方法

可以看到 controller 先执行完成然后返回状态,接着 方法才开始执行。

错误

Spring之AOP奇葩报错:Null return value from advice does not match primitive return type for
原因是返回为null 基本类型要用包装类型。

总结

1 使用了@Async的方法,会被当成是一个子线程,所有整个sendSms方法,会在主线程执行完了之后执行

2 同一个类中,一个方法调用另外一个有@Async的方法,注解是不会生效的!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

猜你在找的Springboot相关文章