springboot @Async 异步调用接口处理数据
2021-11-23 本文已影响0人
明明德撩码
@Async 异步背景
新增的数据需要分发给下游业务系统,由于下游业务系统状态未知,所以需要异步发送数据给下游业务系统。
系统生效按钮--->controller新增-->异步调用servcie--->数据集成
在springboot框架中实现步骤
首先在启动类上加上@EnableAsync注解开启项目的异步调用功能,其次需异步调用的方法上加上注解 @Async 即可实现方法的异步调用,再次在contorller使用的异步方法添加@Lazy
第一步:在启动类上加上 @EnableAsync 注解

第二步添加现场池
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
public class TaskExecutorBean {
public TaskExecutor getTaskExecutor() {
return new ThreadPoolTaskExecutor();
}
}
第三步:servcie方法添加异步注解@Async

第四步使用:在contorller中使用异步方法

------------------------------------异常说明------------------------------------
注入到controller中的service类不添加@Lazy抛出异常信息如下:
in its raw version as part of a circular reference, but has eventually been wrap 异常问题
言外之意就是循环调用, controller已经为spring的bean了其本身也是多线程的,调用的servcie是单实例的,使用springboot的异步注解,spring会对 exposedObject 和bean 做判断,2个对象是否还相同,由于使用@Async注解后这2个对象不再一样,必须添加@Lazy方式,异常问题消失。
参考:https://blog.csdn.net/zhangdeing/article/details/108939877