import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 自定义的 TaskPoolConfig
* 增加 TaskDecorator 属性的配置
*
* @author wang
*/
@Configuration
public class TaskPoolConfig {
/**
*获取当前机器CPU数量
*/
private static final int CPU = Runtime.getRuntime().availableProcessors();
/**
*核心线程数(默认线程数)
*/
private static final int CORE_POOL_SIZE = CPU;
/**
*最大线程数
*/
private static final int MAX_POOL_SIZE = CPU * 2;
/**
*允许线程空闲时间(单位:默认为秒)
*/
private static final int KEEP_ALIVE_TIME = 60;
/**
*缓冲队列数
*/
private static final int QUEUE_CAPACITY = 200;
/**
*线程池名前缀
*/
private static final String THREAD_NAME_PREFIX = "wflTaskExecutor-";
@Bean("wflTaskExecutor")
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 核心线程数(默认线程数)
executor.setCorePoolSize(CORE_POOL_SIZE);
// 最大线程数
executor.setMaxPoolSize(MAX_POOL_SIZE);
// 缓冲队列数
executor.setQueueCapacity(QUEUE_CAPACITY);
// 允许线程空闲时间 s
executor.setKeepAliveSeconds(KEEP_ALIVE_TIME);
// 线程池名前缀
executor.setThreadNamePrefix(THREAD_NAME_PREFIX);
// 线程池对拒绝任务的处理策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 增加 TaskDecorator 属性的配置
executor.setTaskDecorator(new ContextDecorator());
executor.initialize();
return executor;
}
}
import org.springframework.core.task.TaskDecorator;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
/**
* 线程上下文拷贝 TaskDecorator
* @author wang
*/
public class ContextDecorator implements TaskDecorator {
@Override
public Runnable decorate(Runnable runnable) {
RequestAttributes context = RequestContextHolder.currentRequestAttributes();
return () -> {
try {
RequestContextHolder.setRequestAttributes(context);
runnable.run();
} finally {
RequestContextHolder.resetRequestAttributes();
}
};
}
}