在多線程中 feign 調用,服務提供方拿不到 request 的錯誤


問題

executor.submit(() -> {feignClient.queryData()}

上面的代碼,在服務的提供方,queryData()中,獲取 request 中的內容時,為空。

解決

HttpServletRequest 默認是存在一個 ThreadLocal 中的,新開一個線程會丟失 request。
在開啟新的線程執行 feign 調用之前,執行一下下面這行代碼,將 request 暴露給子線程就可以了

RequestContextHolder.setRequestAttributes(RequestContextHolder.getRequestAttributes(), true);

方法注釋

/**
 * Bind the given RequestAttributes to the current thread.
 * @param attributes the RequestAttributes to expose,
 * or {@code null} to reset the thread-bound context
 * @param inheritable whether to expose the RequestAttributes as inheritable
 * for child threads (using an {@link InheritableThreadLocal})
 */


免責聲明!

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



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