spring 线程池中,如何使用theadlocal上下文

依赖

<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>transmittable-thread-local</artifactId>
</dependency>

使用

public class AsyncThreadPoolConfiguration implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
        // TODO 配置具体参数
        threadPool.initialize();

        // 重点:使用 TTL 提供的 TtlExecutors
        return TtlExecutors.getTtlExecutor(threadPool);
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SimpleAsyncUncaughtExceptionHandler();
    }
}

public final class ThreadContext {
    // 只需替换 InheritableThreadLocal 为 TransmittableThreadLocal 即可
    private static final ThreadLocal<Long> USER_ID_LOCAL = new TransmittableThreadLocal<>();

    public static Long getUserId() {
        return USER_ID_LOCAL.get();
    }

    public static void setUserId(Long userId) {
        USER_ID_LOCAL.set(userId);
    }

    public static void clear() {
        USER_ID_LOCAL.remove();
    }
}

 

转自  https://www.jianshu.com/p/4093add7f2cd

 

posted @ 2023-01-13 09:45  蟑螂恶霸的开发笔记  阅读(96)  评论(0编辑  收藏  举报