spring boot2 多线程 异步非阻塞请求 如何在异步任务中获取注入的对象?

sowork
  • 200

当我多线程异步处理任务时,主线程已经返回响应,在多线程通过调用外部服务获取内容时告知 Cannot ask for request attribute - request is not active anymore!

@Service
@Slf4j
public class EquityDataServiceImpl extends ServiceImpl<TestMapper, Test> implements TestService {

    @Autowired
    private testApi testApi;
    
    private List<String> getRemoteInfo() {
        // 子线程当执行到这里的时候,会报上面的错误
        List<String> result = test.getRemoteInfo(url);
        return result;
    }
    
}
  • 线程池初始化逻辑
@Configuration
public class ThreadPoolConfig {

    /**
     * IO 异步
     *
     * @return
     */
    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setTaskDecorator(new ContextCopyingDecorator());
        threadPoolTaskExecutor.setKeepAliveSeconds(30);
        threadPoolTaskExecutor.setAllowCoreThreadTimeOut(true);
        threadPoolTaskExecutor.setCorePoolSize(30);
        threadPoolTaskExecutor.setMaxPoolSize(100);
        threadPoolTaskExecutor.setQueueCapacity(2000);
    }
}
评论
阅读 808
2 个回答
✓ 已被采纳

更新到spring boot 2.0.6解决了

可以选择写个重载方法,传递注入成功对象!

getRemoteInfo(testApi testApi)
撰写回答

登录后参与交流、获取后续更新提醒

宣传栏