在多线程中 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})
 */
posted @   淡蓝色光  阅读(2474)  评论(0编辑  收藏  举报
编辑推荐:
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
阅读排行:
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· Ai满嘴顺口溜,想考研?浪费我几个小时
· Browser-use 详细介绍&使用文档
· 软件产品开发中常见的10个问题及处理方法
点击右上角即可分享
微信分享提示