在多线程中 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 @ 2021-02-25 19:51  淡蓝色光  阅读(2184)  评论(0编辑  收藏  举报