解决线程池ExecutorService里面slf4j打log无法拿到外部写入MDC的上下文

public class XHSThreadPoolExecutor extends ThreadPoolExecutor {

    public XHSThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
    }

    @Override
    public void execute(Runnable command) {
        Map map = MDC.getCopyOfContextMap();
        super.execute(()-> {
            MDC.setContextMap(map);
            command.run();
        });
    }
}

然后实例化ExecutorService

@Configuration
public class ExecutorServiceConfig {

    @Bean
    public ExecutorService getExecutorService() {
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                .setNameFormat("asyncExecutorService-%d").build();
        ExecutorService executorService = new XHSThreadPoolExecutor(200,
                2000, 60L , TimeUnit.SECONDS, new SynchronousQueue<>(), namedThreadFactory);
        return executorService;
    }
}

你可能感兴趣的:(解决线程池ExecutorService里面slf4j打log无法拿到外部写入MDC的上下文)