zoukankan      html  css  js  c++  java
  • 在多线程中 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})
     */
    
  • 相关阅读:
    集合使用技巧
    集合总结
    Eclipse快捷键大全
    集合去掉重复元素的两种方式
    Collection集合的三种遍历方式
    win基本流程
    url
    StringBuffer7
    StringBuffer8
    StringBuffer6
  • 原文地址:https://www.cnblogs.com/lighter-blog/p/14448938.html
Copyright © 2011-2022 走看看