前言
研發(fā)中有一些操作需要用到了異步調(diào)用,但是傳遞request的時候生命周期會提前結(jié)束晋控,導(dǎo)致傳遞參數(shù)獲取不到
示例
創(chuàng)建decorator
public class ContextDecorator implements TaskDecorator {
@Override
public Runnable decorate(Runnable r) {
RequestAttributes context = RequestContextHolder.currentRequestAttributes();
return () -> {
try {
RequestContextHolder.setRequestAttributes(context);
r.run();
} finally {
RequestContextHolder.resetRequestAttributes();
}
};
}
}
配置線程池
@Configuration
public class TaskPoolConfig {
@Bean("taskExecutor")
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 核心線程數(shù)(默認(rèn)線程數(shù))
executor.setCorePoolSize(10);
// 最大線程數(shù)
executor.setMaxPoolSize(20);
// 緩沖隊列數(shù)
executor.setQueueCapacity(200);
// 允許線程空閑時間(單位:默認(rèn)為秒)
executor.setKeepAliveSeconds(60);
// 線程池名前綴
executor.setThreadNamePrefix("task-executor-");
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(60);
// 增加 TaskDecorator 屬性的配置
executor.setTaskDecorator(new ContextDecorator());
// 線程池對拒絕任務(wù)的處理策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
}
-end-