子线程如何获取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多平台发布

相关推荐
Java程序员-小白19 分钟前
使用java -jar命令指定VM参数-D运行jar包报错问题
java·开发语言·jar
ClearViper31 小时前
Java的多线程笔记
java·开发语言·笔记
全栈凯哥2 小时前
Java详解LeetCode 热题 100(17):LeetCode 41. 缺失的第一个正数(First Missing Positive)详解
java·算法·leetcode
神经毒素2 小时前
WEB安全--Java安全--LazyMap_CC1利用链
java·开发语言·网络·安全·web安全
逸夕2 小时前
httpclient请求出现403
java
呆呆洁ᵔ·͈༝·͈ᵔ2 小时前
配置集群-日志聚集操作
java·ide·eclipse
lyrhhhhhhhh3 小时前
Spring 模拟转账开发实战
java·后端·spring
banzhenfei3 小时前
xp_cmdshell bcp 导出文件
java·数据库·sql
带刺的坐椅3 小时前
SpringBoot3 使用 SolonMCP 开发 MCP
java·ai·springboot·solon·mcp
胡斌附体3 小时前
微服务调试问题总结
java·微服务·架构·调试·本地·夸微服务联调