子线程获取Request


文章目录


子线程获取Request

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

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

private static final ThreadLocal<RequestAttributes> requestAttributesHolder =
      new NamedThreadLocal<RequestAttributes>("Request attributes");

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

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

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

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

这是什么原理?

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方法

ThreadLocalMap getMap(Thread t) {
   return t.inheritableThreadLocals;
}

参考文献

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

拾光师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值