springboot 在同一个文件中调用@Async方法,正常异步请求
背景: 都知道,在同一个文件中调用@Async 注解的方案,异步会失效。其中通过重新注册bean 是可以做到的。
下面是代码:
@Resource
private ApplicationContext applicationContext; --项目引入
在调用方法时改造一下:
getUserName() 改为
applicationContext.getBean(当前class名.class).getUserName() -=就会正常异步请求了。
ps:sprigboot 线程池 构建:
@Configuration
@EnableAsync
public class AsyncConfig{
@Bean("dealExecutor")
public ThreadPoolTaskExecutor dealExecutor(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(5);
executor.setQueueCapacity(5000);
executor.setKeepAliveSeconds(180);
executor.setThreadNamePrefix("custom-async-dealExecutor");
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(30);
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
executor.initialize();
return executor;
}
}