@Async 自定义线程池
自定义线程池逻辑
@Component
@Slf4j
public class ThreadPoolConfig implements AsyncConfigurer {
private static final float BLOCKING_COEFFICIENT = 0.85F;
@Override
@Bean(CommonConstant.ASYNC_EXECUTOR_CUSTOM)
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
int poolSize = (int) (Runtime.getRuntime().availableProcessors() / (1 - BLOCKING_COEFFICIENT));
threadPool.setCorePoolSize(poolSize);
threadPool.setMaxPoolSize(poolSize);
threadPool.setQueueCapacity(poolSize*2);
threadPool.setKeepAliveSeconds(60);
threadPool.setWaitForTasksToCompleteOnShutdown(true);
threadPool.setAwaitTerminationSeconds(60 * 15);
threadPool.setThreadNamePrefix("async-task-thread-pool-");
threadPool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
threadPool.initialize();
log.info(">>>>>>>>>>>>>>> 开启自定义异步线程池");
return threadPool;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new MyAsyncExceptionHandler();
}
static class MyAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
@Override
public void handleUncaughtException(Throwable throwable, Method method, Object... obj) {
log.error(">>>>>>>>>>>>>>> 自定义线程池捕获线程异常信息 {}",throwable.toString());
log.error("Exception message - " + throwable.getMessage());
log.error("Method name - " + method.getName());
for (Object param : obj) {
log.info("Parameter value - " + param);
}
}
}
}
使用
@Async(CommonConstant.ASYNC_EXECUTOR_CUSTOM)
其他
public static final String ASYNC_EXECUTOR_CUSTOM = "async-executor-custom";