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

相关推荐
czhc11400756632 分钟前
Java1112 基类 c#vscode使用 程序结构
android·java·数据库
嫂子的姐夫2 分钟前
23-MD5+DES+Webpack:考试宝
java·爬虫·python·webpack·node.js·逆向
缪懿11 分钟前
JavaEE:多线程基础,多线程的创建和用法
java·开发语言·学习·java-ee
Chan1615 分钟前
Java 集合面试核心:ArrayList/LinkedList 底层数据结构,HashMap扩容机制详解
java·数据结构·spring boot·面试·intellij-idea
Boop_wu15 分钟前
[Java EE] 多线程 -- 初阶(2)
java·开发语言·jvm
q***985218 分钟前
Spring Boot(快速上手)
java·spring boot·后端
凌凌022 分钟前
macOS安装SDKMAN
java
百***920224 分钟前
Spring Boot 多数据源解决方案:dynamic-datasource-spring-boot-starter 的奥秘(上)
java·spring boot·后端
青山的青衫29 分钟前
【Java基础07】链表
java·开发语言·链表
麦麦鸡腿堡35 分钟前
Java事件处理机制
java·开发语言·python