自定装饰器
import org.slf4j.MDC;
import org.springframework.core.task.TaskDecorator;
import java.util.Map;
public class ComTaskDecorator implements TaskDecorator {
@Override
public Runnable decorate(Runnable runnable) {
// 主线程可执行的代码
Map<String, String> copyOfContextMap = MDC.getCopyOfContextMap();
return () -> {
// 子线程执行的代码
MDC.setContextMap(copyOfContextMap);
runnable.run();
};
}
}
使用自定义的装饰器
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
public class ThreadPoolConfiguration {
@Bean
public ThreadPoolTaskExecutor customThreadPoolTaskExecutor() {
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
//核心线程数
threadPoolTaskExecutor.setCorePoolSize(5);
//核心线程若处于闲置状态的话,超过一定的时间(KeepAliveTime),就会销毁掉。
threadPoolTaskExecutor.setAllowCoreThreadTimeOut(true);
//最大线程数
threadPoolTaskExecutor.setMaxPoolSize(10);
//配置队列大小
threadPoolTaskExecutor.setQueueCapacity(300);
//加入装饰器
threadPoolTaskExecutor.setTaskDecorator(new ComTaskDecorator());
//配置线程池前缀
threadPoolTaskExecutor.setThreadNamePrefix("test-log-");
//拒绝策略:只要线程池未关闭,该策略直接在调用者线程中串行运行被丢弃的任务,显然这样不会真的丢弃任务,但是可能会造成调用者性能急剧下降
threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
threadPoolTaskExecutor.initialize();
return threadPoolTaskExecutor;
}
}
标签:隔离,TaskDecorator,springframework,线程,org,import,threadPoolTaskExecutor
From: https://www.cnblogs.com/shareToAll/p/18342600