关于程序员:子线程如何获取Request

8次阅读

共计 1293 个字符,预计需要花费 4 分钟才能阅读完成。

子线程获取 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");

然而有时候子线程就是须要获取到以后申请怎么办呢?

<!– more –>

此时就须要将 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;}

https://zhhll.icu/2020/javaweb/ 问题 /7. 子线程获取 Request/

本文由 mdnice 多平台公布

正文完
 0