子线程获取Request
子线程获取Request
原文链接 https://zhhll.icu/2020/javaweb/问题/7.子线程获取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;
}
本文来自博客园,作者:拾光师,转载请注明原文链接:https://www.cnblogs.com/life-time/p/17864380.html 个人博客-> https://zhhll.icu
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~