@Async默认的线程池为SimpleAsyncTaskExecutor。

可自定义

@Async调用线程池,推荐使用自定义线程池的模式。自定义线程池常用方案:重新实现接口AsyncConfigurer。


@Configuration
@EnableAsync
@Slf4j
class SpringAsyncConfigurer extends AsyncConfigurerSupport {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
        threadPool.setCorePoolSize(3);
        threadPool.setMaxPoolSize(3);
        threadPool.setWaitForTasksToCompleteOnShutdown(true);
        threadPool.setAwaitTerminationSeconds(60 * 15);
        return threadPool;
    }

  @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (ex, method, params) -> log.error("执行异步任务异常:{}", method, ex);
    }
}
作者:张三  创建时间:2022-06-02 20:41
最后编辑:张三  更新时间:2024-10-16 21:30