依赖
<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
标签:spring,theadlocal,public,线程,USER,new,static,LOCAL,ID From: https://www.cnblogs.com/xiaodu9499/p/17048629.html