自定义执行器
@EnableAsync
@Configuration
public class SpringAsyncTaskConfiguration {
@Primary
@Bean
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(8);
executor.setMaxPoolSize(Math.max(8, Runtime.getRuntime().availableProcessors() * 2));
executor.setQueueCapacity(2048);
executor.setKeepAliveSeconds(60);
executor.setThreadNamePrefix("spring-async-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(60);
return executor;
}
@Bean
public TaskExecutor customTaskExecutor() {
return buildSequentialExecutor("customTaskExecutor", 50000);
}
/**
* 创建一个可以顺序执行的执行器,通过设置线程池只有一个线程和队列的方式来保证顺序执行
* @param executorName
* @param queueSize
* @return
*/
private ThreadPoolTaskExecutor buildSequentialExecutor(String executorName, int queueSize) {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(1);
executor.setMaxPoolSize(1);
executor.setQueueCapacity(queueSize);
executor.setKeepAliveSeconds(60);
executor.setThreadNamePrefix("spring-async-".concat(executorName));
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(60);
return executor;
}
}
使用
用注解@Async的时候指定执行器的名称即可,即指定beanName
@Async("customTaskExecutor")
bla...bla...