做网站和做微信小程序,wordpress 建网站,美食分享网站设计,重庆专门做网站的公司子线程获取Request 有时候在进行业务处理时对于一些对于业务不那么重要且对于返回结果无关的情况会开启一个新的线程进行处理#xff0c;但是在开启新线程进行处理时发现无法从RequestContextHolder中获取到当前的请求#xff0c;取出来是null 这是因为RequestContextHolder中… 子线程获取Request 有时候在进行业务处理时对于一些对于业务不那么重要且对于返回结果无关的情况会开启一个新的线程进行处理但是在开启新线程进行处理时发现无法从RequestContextHolder中获取到当前的请求取出来是null 这是因为RequestContextHolder中的信息都是存储在ThreadLocal中的而ThreadLocal中的数据是使用线程进行查找的不是该线程存储的是无法查找到的 private static final ThreadLocalRequestAttributes requestAttributesHolder new NamedThreadLocalRequestAttributes(Request attributes);private static final ThreadLocalRequestAttributes inheritableRequestAttributesHolder new NamedInheritableThreadLocalRequestAttributes(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;} https://zhhll.icu/2020/javaweb/问题/7.子线程获取Request/ 本文由 mdnice 多平台发布