@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);
}
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
使用
@Async(CommonConstant.ASYNC_EXECUTOR_CUSTOM)
其他
public static final String ASYNC_EXECUTOR_CUSTOM = "async-executor-custom";