在多线程中 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