作者:手机用户2502924593 | 来源:互联网 | 2023-07-29 16:31
今天我们分析多线程场景下异步操作子线程获取不到主线程request信息问题解决及源码解析:
一,共享request问题解决:
1、先说使用,主线程核心设置代码:
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
RequestContextHolder.setRequestAttributes(servletRequestAttributes, true);//设置子线程共享
2、主线程设置后,子线程就可以直接使用了,可以断定或打印出来相关信息,子线程相关代码:
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = servletRequestAttributes.getRequest();
String userName = request.getHeader("userName");
String userId = request.getHeader("userId ");
如果设置成功,request不为空,且能查到相关参数。如图:
继续看:
二、源码解析:
1、关键入口RequestContextHolder类,意思是以线程绑定的的形式保存web请求的相关信息的holder类,通过设置inheritable属性来决定是否能被子线程继承;该类里面包含两个ThreadLocal全局属性;进入 setRequestAttributes(servletRequestAttributes, true);方法源码
//类上共享变量
private static final boolean jsfPresent =ClassUtils.isPresent("javax.faces.context.FacesContext", RequestContextHolder.class.getClassLoader());
//控制主线程的 ThreadLocalprivate static final ThreadLocal requestAttributesHolder &#61;new NamedThreadLocal<>("Request attributes");
//控制子线程的 ThreadLocalprivate static final ThreadLocal inheritableRequestAttributesHolder &#61;new NamedInheritableThreadLocal<>("Request context");
//核心源码public static void setRequestAttributes(&#64;Nullable RequestAttributes attributes, boolean inheritable) {if (attributes &#61;&#61; null) {resetRequestAttributes();}else {if (inheritable) {//传true// 就是把request的属性放入到inheritableRequestAttributesHolder 中,供子类继承inheritableRequestAttributesHolder.set(attributes);requestAttributesHolder.remove();//子线程中删除主线程的信息}else {//传falserequestAttributesHolder.set(attributes);//设置主线程使用inheritableRequestAttributesHolder.remove();//不共享设置}}}
2、子线程获取主线程的request的属性 请看下图&#xff0c;子线程中 requestAttributesHolder.get() 获取属性为空&#xff0c;就会从inheritableRequestAttributesHolder 中去获取属性&#xff1a;
点击 RequestContextHolder.getRequestAttributes();方法&#xff1a;
&#64;Nullable
public static RequestAttributes getRequestAttributes() {RequestAttributes attributes &#61; requestAttributesHolder.get();if (attributes &#61;&#61; null) {//负责主线程的信息为空&#xff0c;就去负责子线程的作用域中取attributes &#61; inheritableRequestAttributesHolder.get();}return attributes;
}
到此你就会豁然开朗了。
3、延伸问题&#xff1a;上一步 requestAttributesHolder 属性是在什么时候放进去的呢&#xff0c;从类的说明中看看到 DispatcherServlet 类已经默认把web request的属性放到了 requestAttributesHolder 中&#xff0c;DispatcherServlet 继承自 FrameworkServlet&#xff0c;在FrameworkServlet 的 processRequest()方法中的 resetContextHolders会把web request的属性放入到requestAttributesHolder 中&#xff0c;具体源码如下&#xff1a;public class DispatcherServlet extends FrameworkServlet 点击&#xff1a;FrameworkServlet类
&#64;Overrideprotected void service(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {HttpMethod httpMethod &#61; HttpMethod.resolve(request.getMethod());if (httpMethod &#61;&#61; HttpMethod.PATCH || httpMethod &#61;&#61; null) {processRequest(request, response);//处理请求核心代码&#xff0c;进入}else {super.service(request, response);}}
点击&#xff1a;processRequest 方法&#xff1a;
protected final void processRequest(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {long startTime &#61; System.currentTimeMillis();Throwable failureCause &#61; null;LocaleContext previousLocaleContext &#61; LocaleContextHolder.getLocaleContext();LocaleContext localeContext &#61; buildLocaleContext(request);RequestAttributes previousAttributes &#61; RequestContextHolder.getRequestAttributes();ServletRequestAttributes requestAttributes &#61; buildRequestAttributes(request, response, previousAttributes);WebAsyncManager asyncManager &#61; WebAsyncUtils.getAsyncManager(request);asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor());initContextHolders(request, localeContext, requestAttributes);try {doService(request, response);}catch (ServletException | IOException ex) {failureCause &#61; ex;throw ex;}catch (Throwable ex) {failureCause &#61; ex;throw new NestedServletException("Request processing failed", ex);}finally {//核心代码resetContextHolders(request, previousLocaleContext, previousAttributes);if (requestAttributes !&#61; null) {requestAttributes.requestCompleted();}logResult(request, response, failureCause, asyncManager);publishRequestHandledEvent(request, response, startTime, failureCause);}}
点击&#xff1a;resetContextHolders 方法&#xff1a;
private void resetContextHolders(HttpServletRequest request,&#64;Nullable LocaleContext prevLocaleContext, &#64;Nullable RequestAttributes previousAttributes) {LocaleContextHolder.setLocaleContext(prevLocaleContext, this.threadContextInheritable);//主线程设置request信息RequestContextHolder.setRequestAttributes(previousAttributes, this.threadContextInheritable);
}
4、到此异步子线程共享主线程request属性的源码剖析已经结束。需要说明的是这种共享方式适合用于主线程等待子线程完成任务后在结束的情况&#xff0c;否则主线程调用主线程先与子线程结束的话主线程的request 会被销毁&#xff0c;子线程还是共享不了主线程的request属性。针对后面的情况给出一个解决方案&#xff0c;那就是子线程都结束后通知主线程结束。