自定义线程池并拷贝线程上下文


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 自定义的 TaskPoolConfig
 * 增加 TaskDecorator 属性的配置
 *
 * @author wang
 */
@Configuration
public class TaskPoolConfig {
    /**
     *获取当前机器CPU数量
     */
    private static final int CPU = Runtime.getRuntime().availableProcessors();
    /**
     *核心线程数(默认线程数)
     */
    private static final int CORE_POOL_SIZE = CPU;
    /**
     *最大线程数
     */
    private static final int MAX_POOL_SIZE = CPU * 2;
    /**
     *允许线程空闲时间(单位:默认为秒)
     */
    private static final int KEEP_ALIVE_TIME = 60;
    /**
     *缓冲队列数
     */
    private static final int QUEUE_CAPACITY = 200;
    /**
     *线程池名前缀
     */
    private static final String THREAD_NAME_PREFIX = "wflTaskExecutor-";


    @Bean("wflTaskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数(默认线程数)
        executor.setCorePoolSize(CORE_POOL_SIZE);
        // 最大线程数
        executor.setMaxPoolSize(MAX_POOL_SIZE);
        // 缓冲队列数
        executor.setQueueCapacity(QUEUE_CAPACITY);
        // 允许线程空闲时间 s
        executor.setKeepAliveSeconds(KEEP_ALIVE_TIME);
        // 线程池名前缀
        executor.setThreadNamePrefix(THREAD_NAME_PREFIX);
        // 线程池对拒绝任务的处理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        // 增加 TaskDecorator 属性的配置
        executor.setTaskDecorator(new ContextDecorator());
        executor.initialize();

        return executor;
    }
}

import org.springframework.core.task.TaskDecorator;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

/**
 * 线程上下文拷贝 TaskDecorator
 * @author wang
 */
public class ContextDecorator implements TaskDecorator {

    @Override
    public Runnable decorate(Runnable runnable) {
        RequestAttributes context = RequestContextHolder.currentRequestAttributes();
        return () -> {
            try {
                RequestContextHolder.setRequestAttributes(context);
                runnable.run();
            } finally {
                RequestContextHolder.resetRequestAttributes();
            }
        };
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值