使用多線程時,傳遞 request 對象丟失


1.原因描述

我們在工作中遇到耗時的一些操作時我們會使用多線程或者mq來解決以便提高程序的響應速度。但是使用多線程時遇到一個問題,我單獨開一個線程去進行其他邏輯處理時,在發送消息之前(未開啟多線程時)我們是可以獲取到 request 信息的,但是在新開的線程中確是無法獲取到 request 信息(request is  null)。

2.代碼演示

主線程代碼

 

 

 

子線程代碼

 

 

 3.錯誤描述

 由上圖可知子線程無法獲取到 request 信息,直接報了 java.lang.NullPointerException。

原因:request 信息是存儲在 ThreadLocal 中的,所以子線程根本無法獲取到主線程的  request 信息。

/**
* 返回當前線程上下文request信息
*
* @return
*/
public static HttpServletRequest getCurrentRequestInfo() {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
return servletRequestAttributes.getRequest();
}

源碼如下:

private static final ThreadLocal<RequestAttributes> requestAttributesHolder =
new NamedThreadLocal<RequestAttributes>("Request attributes");
/**
* Return the RequestAttributes currently bound to the thread.
* @return the RequestAttributes currently bound to the thread,
* or {@code null} if none bound
*/
public static RequestAttributes getRequestAttributes() {
RequestAttributes attributes = requestAttributesHolder.get();
if (attributes == null) {
attributes = inheritableRequestAttributesHolder.get();
}
return attributes;
}

4.解決方案

在新開子線程之前 新增二行代碼,如下,

// 將RequestAttributes對象設置為子線程共享
ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
RequestContextHolder.setRequestAttributes(sra, true);

子線程代碼

 

子線程代碼

 

 到此問題完美解決,如果想要深入了解原因  需要看源碼。

 

獲取當前線程上下文信息方法地址:https://www.cnblogs.com/ming-blogs/p/12754837.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM