使用TaskDecorator装饰器实现再线程隔离下的数据复制

自定装饰器

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("log-");
        //拒绝策略
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }
}
posted @ 2024-08-05 09:25  品书读茶  阅读(52)  评论(0编辑  收藏  举报