初始化线程池
@Configuration
public class SpringAsyncConfig implements AsyncConfigurer {
/**
* 核心线程数
*/
private int corePoolSize = 20;
/**
* 最大线程数
*/
private int maximumPoolSize = 1000;
/**
* 线程空闲时间
*/
private int keepAliveTime = 60;
/**
* 阻塞队列容量
*/
private int queueCapacity = 9999;
/**
* 构建线程工厂
*/
@Override
@Bean("asyncExecutor")
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maximumPoolSize);
executor.setKeepAliveSeconds(keepAliveTime);
executor.setQueueCapacity(queueCapacity);
executor.setThreadNamePrefix("TreadName:hik:");
executor.setRejectedExecutionHandler((Runnable r,ThreadPoolExecutor exe) -> {
log.warn("当前任务线程池队列已满.");
});
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new AsyncUncaughtExceptionHandler() {
@Override
public void handleUncaughtException(Throwable ex, Method method, Object... params) {
log.error("线程池执行任务发生未知异常:", ex);
}
};
}
}
线程池使用
@Async(“asyncExecutor”)