package com.webmanage.config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.AsyncConfigurer; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import javax.annotation.Resource; import java.lang.reflect.Method; import java.util.concurrent.Executor; import java.util.concurrent.ThreadPoolExecutor; @Configuration public class AsyncConfig implements AsyncConfigurer { private static final Logger log = LoggerFactory.getLogger(AsyncConfig.class); @Resource private AsyncExecutorProperties properties; @Override @Bean("asyncExecutor") public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(properties.getCorePoolSize()); executor.setMaxPoolSize(properties.getMaxPoolSize()); executor.setQueueCapacity(properties.getQueueCapacity()); executor.setKeepAliveSeconds(properties.getKeepAliveSeconds()); executor.setThreadNamePrefix(properties.getThreadNamePrefix()); executor.setWaitForTasksToCompleteOnShutdown(properties.isWaitForTasksToCompleteOnShutdown()); executor.setAwaitTerminationSeconds(properties.getAwaitTerminationSeconds()); // 饱和策略:调用方线程执行,避免任务被丢弃 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); executor.initialize(); return executor; } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return new AsyncUncaughtExceptionHandler() { @Override public void handleUncaughtException(Throwable ex, Method method, Object... params) { log.error("异步任务执行异常, method={}, params={}", method, params, ex); } }; } }