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

相关推荐
夫唯不争,故无尤也1 分钟前
JavaWeb流式传输速查宝典
java·流式传输
苏小瀚1 小时前
算法---位运算
java·算法
Camel卡蒙1 小时前
数据结构——二叉搜索树Binary Search Tree(介绍、Java实现增删查改、中序遍历等)
java·开发语言·数据结构
2401_841495641 小时前
【数据结构】基于Floyd算法的最短路径求解
java·数据结构·c++·python·算法··floyd
珹洺1 小时前
Java-Spring入门指南(二十七)Android Studio 第一个项目搭建与手机页面模拟器运行
java·spring·android studio
程序猿DD2 小时前
Java 25 中的 6 个新特性解读
java·后端
稻草猫.2 小时前
文件 IO
java·笔记·后端·java-ee·idea
laopeng3012 小时前
基于Spring AI Deep Researcher Agent
java·人工智能·spring
子豪-中国机器人2 小时前
《C++ STL 基础入门》教案
java·开发语言
java_t_t2 小时前
集合工具类
java·集合