OpenFeign远程调用丢失请求头问题解决办法


同步调用

@Configuration
public class FeignConfiguration {

    //feign远程调用丢失请求头问题
    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor(){
        return template -> {
            ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            String cookie = request.getHeader("Cookie");
            template.header("Cookie",cookie);
        };
    }
}

我这里只添加了header中的Cookie,当然也可以遍历header,把所有的都添加到新的请求。解决办法跟Gateway丢失请求头类似。https://www.cnblogs.com/wwjj4811/p/13937694.html

异步调用

当我们使用异步调用openfeign,上述代码就会报空指针,获取不到当前的请求。

解决方法如下:

我们先获取到当前请求,再分享给子线程。

RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
    RequestContextHolder.setRequestAttributes(attributes);
    feign.doService();
}, executor);


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM