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