子线程如何获取Request

子线程获取Request

有时候在进行业务处理时对于一些对于业务不那么重要且对于返回结果无关的情况会开启一个新的线程进行处理,但是在开启新线程进行处理时发现无法从RequestContextHolder中获取到当前的请求,取出来是null

这是因为RequestContextHolder中的信息都是存储在ThreadLocal中的,而ThreadLocal中的数据是使用线程进行查找的,不是该线程存储的,是无法查找到的

java 复制代码
private static final ThreadLocal<RequestAttributes> requestAttributesHolder =
      new NamedThreadLocal<RequestAttributes>("Request attributes");

private static final ThreadLocal<RequestAttributes> inheritableRequestAttributesHolder =
      new NamedInheritableThreadLocal<RequestAttributes>("Request context");

但是有时候子线程就是需要获取到当前请求怎么办呢?

此时就需要将RequestAttributes对象设置为子线程共享的,在开启子线程之前

java 复制代码
// 主线程先获取到请求信息
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
// 设置子线程共享
RequestContextHolder.setRequestAttributes(requestAttributes,true);

这是什么原理?

java 复制代码
public static void setRequestAttributes(RequestAttributes attributes, boolean inheritable) {
   if (attributes == null) {
      resetRequestAttributes();
   }
   else {
      if (inheritable) {  // 如果为true,则将信息存储在inheritableRequestAttributesHolder中
         inheritableRequestAttributesHolder.set(attributes);
         requestAttributesHolder.remove();
      }
      else {
         requestAttributesHolder.set(attributes);
         inheritableRequestAttributesHolder.remove();
      }
   }
}

可以看到NamedInheritableThreadLocal重写了getMap方法

java 复制代码
ThreadLocalMap getMap(Thread t) {
   return t.inheritableThreadLocals;
}

zhhll.icu/2020/javawe...

本文由mdnice多平台发布

相关推荐
captain3762 小时前
多线程线程安全问题
java·java-ee
CoderYanger3 小时前
A.每日一题:1979. 找出数组的最大公约数
java·程序人生·算法·leetcode·面试·职场和发展·学习方法
灵极海3 小时前
LangChain4j RAG 实战完整指南:从入门到踩坑
java·langchain
yaoxin5211233 小时前
476. Java 反射 - 调用方法
java·开发语言
Ivanqhz4 小时前
Rust Lazy浅析
java·javascript·rust
bksczm4 小时前
Linux之日志和线程池、内存池
java·开发语言
笨蛋不要掉眼泪4 小时前
Java虚拟机:对象复活、引用强度与Stop-The-World
java·开发语言·jvm
凤山老林5 小时前
SpringBoot实战:构建优雅的全局异常处理机制
java·springboot·异常处理
小Ti客栈5 小时前
Spring Boot 整合 Swagger2 和 Knife4j实现接口文档与可视化调试
java·spring boot·后端
梅头脑5 小时前
ThreadLocalMap里几十万个死Entry——排查了半天OOM,根因就一行finally没写
java