SpringBoot自定义异步任务线程池

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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容