1、问题描述
自己配置的Executor(自己创建的线程池)
目录
(1)方法1:直接用EnableScheduling注解里头自己定义的全局线程池:
比方说:
@Configuration
public class ThreadPoolConfig {
@Bean(value = "selfExecutor")
public Executor createDefaultIOExecutor() {
int coreCount = Runtime.getRuntime().availableProcessors() * 2;
NamedThreadFactory namedThreadFactory = new NamedThreadFactory("statistics-IO-thread-pool");
Executor executor = new ThreadPoolExecutor(
coreCount
, coreCount
, 60
, TimeUnit.SECONDS
, new LinkedBlockingQueue<>(1024)
, namedThreadFactory
, new ThreadPoolExecutor.CallerRunsPolicy()
);
return executor;
}
}
会和定时任务的Executor的冲突,如果在启动类上添加了@EnableScheduled 注解的话。
启动类:
@EnableScheduling
@EnableCaching
public class StoreStatisticsServerApplication {
public static void main(String[] args) {
SpringApplication.run(StoreStatisticsServerApplication.class, args);
}
}
报错:Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'java.util.concurrent.Executor' available: expected single matching bean but found 2: selfExecutor,taskScheduler
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'java.util.concurrent.Executor' available: expected single matching bean but found 2: selfExecutor,taskScheduler
at org.springframework.beans.factory.config.DependencyDescriptor.resolveNotUnique(DependencyDescriptor.java:220)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1284)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1226)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:521)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:497)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:650)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:239)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:130)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessProperties(CommonAnnotationBeanPostProcessor.java:318)
... 34 common frames omitted
2、原因探索
实际上就是spring容器自己管理了全局的线程池,和自己配置的冲突了。可以去看看上述spring项目自己做的定时任务的这个线程池启动的类。
org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor
还有spring自动配置里面的:
org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration#applicationTaskExecutor
因此自己配置了线程池的话,还需要重新配置这个threadpooltaskexecutor,否则:
(1)用重命名bean的方式注入这种方式解决,则可能因为类型不对,注入失败;
(2)修改自己配置的bean的名字为人家写死的bean的名字(“applicationTaskExecutor”),依然有类型不对问题;
3、问题解决:
(1)方法1:直接用EnableScheduling注解里头自己定义的全局线程池:
org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
使用案例
@Resource
private ThreadPoolTaskExecutor threadPoolTaskExecutor;
/**
* 获取按照状态区分的订单信息
* @param statParamRequest
* @return
*/
@Override
public PageableResponse<List<StatBillStatusVO>> getStatusBillInfoList(StatParamRequest statParamRequest, OrderStatTagEnum orderStatTagEnum) {
// 业务处理代码1XXX
// 计算单据的占比和设值
CompletableFuture<Void> billInfo = CompletableFuture.runAsync(() -> {
this.getBillInfo(statBillStatusVO, orderAgg, finalQuantitySum, finalAmountSum);
}, threadPoolTaskExecutor).exceptionally(throwable -> {
throw new IllegalStateException("计算单据的占比和设值出错,request="+ JsonUtils.toJson(statParamRequest));
});
// 按照状态或来源聚合
CompletableFuture<Void> statusSourceInfo = CompletableFuture.runAsync(() -> {
this.setStatusOrSource(orderAgg, orderStatTagEnum, statBillStatusVO);
}, threadPoolTaskExecutor).exceptionally(throwable -> {
throw new IllegalStateException("按照状态或来源聚合设值出错,request="+ JsonUtils.toJson(statParamRequest));
});
CompletableFuture.allOf(billInfo, statusSourceInfo).join();
// 业务处理代码2XXX
}
(2)方法2:自己开自己的线程池
/**
* @Author: Zeng Yanru
* @Description:
* @DateTime: 2021/7/8 11:05
*/
public class ThreadPoolInit {
public static Executor executor = createDefaultIOExecutor();
public static Executor createDefaultIOExecutor() {
int coreCount = Runtime.getRuntime().availableProcessors() * 2;
NamedThreadFactory namedThreadFactory = new NamedThreadFactory("statistics-IO-thread-pool");
return new ThreadPoolExecutor(
coreCount
, coreCount
, 60
, TimeUnit.SECONDS
, new LinkedBlockingQueue<>(1024)
, namedThreadFactory
, new ThreadPoolExecutor.CallerRunsPolicy()
);
}
}
然后在外部调用即可。最好做成spring容器全部能用的,否则不断创建线程池开销也很大。
(3)方法3:重新配置注解所需线程池
/**
* @Author: Zeng Yanru
* @Description:
* @DateTime: 2021/7/9 9:46
*/
@Configuration
public class DefaultThreadPool {
@Bean("aaa")
public ListenableThreadPoolExecutor createDefaultIOExecutor() {
int coreCount = Runtime.getRuntime().availableProcessors() * 2;
NamedThreadFactory namedThreadFactory = new NamedThreadFactory("statistics-IO-thread-pool1");
return new ListenableThreadPoolExecutor(
coreCount,
coreCount,
60,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(),
namedThreadFactory);
}
// @EnableScheduling注解所需要的线程池,配置则自定义或者按照原本的配置
@Bean(name = "applicationTaskExecutor")
public ThreadPoolTaskExecutor createTreadPoolTaskExecutor() {
int coreCount = Runtime.getRuntime().availableProcessors() * 2;
NamedThreadFactory namedThreadFactory = new NamedThreadFactory("statistics-IO-thread-pool2");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(coreCount);
executor.setMaxPoolSize(coreCount);
executor.setKeepAliveSeconds(60);
// 这个executor的写死的blockingqueue就是linkedblockingqueue
// 其他值不用设置
return executor;
}
}