解决线程池ExecutorService里面slf4j打log无

2019-03-07  本文已影响0人  JoneSnow
public class XHSThreadPoolExecutor extends ThreadPoolExecutor {

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

    @Override
    public void execute(Runnable command) {
        Map<String, String> 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;
    }
}
上一篇下一篇

猜你喜欢

热点阅读