1、默认异步任务线程池
SpringBoot异步任务默认使用的线程池为SimpleAsyncTaskExecutor,其特点如下:
- 默认定义多少异步任务,创建多少线程(创建线程数量太多,占用内存过大,会造成OutOfMemoryError)。
- SimpleAsyncTaskExecutor不提供拒绝策略机制。
- SimpleAsyncTaskExecutor可通过设置参数concurrencyLimit(值为大于或等于0的整数),指定启用的线程数目;默认concurrencyLimit取值为-1,即不启用资源节流。
2、自定义异步任务线程池
@Configuration
public class AsyncThreadPoolConfig implements AsyncConfigurer {
/**
* 自定义线程池
* @return 线程池对象
*/
@Bean
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setCorePoolSize(5);
threadPoolTaskExecutor.setMaxPoolSize(8);
threadPoolTaskExecutor.setQueueCapacity(10);
threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
threadPoolTaskExecutor.initialize();
return threadPoolTaskExecutor;
}
/**
* 自定义异常处理器
* @return 异常处理器对象
*/
@Bean
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
AsyncUncaughtExceptionHandler syncUncaughtExceptionHandler = (ex, method, params) -> ex.printStackTrace();
return syncUncaughtExceptionHandler;
}
}