feign远程调用丢失上下文问题

由于feign远程调用,是重新创建的 request请求,所以远程调用的时候获取不到原生请求的请求头信息,解决feign调用丢失请求头可以加请求拦截器,RequestInterceptor

@Configuration
public class FeignConfig {

    @Bean("/requestInterceptor")
    public RequestInterceptor requestInterceptor(){
        RequestInterceptor requestInterceptor = new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                //拿到刚进来的请求
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                //老的请求头
                HttpServletRequest request = attributes.getRequest();
                String cookie = request.getHeader("Cookie");
                // 给新的请求同步老的请求头
                requestTemplate.header("Cookie",cookie);
            }
        };
        return requestInterceptor;
    }
}

如果是异步调用还可能会丢失上下文,可以从主线程中取出RequestContextHolder然后再给到子线程中,保持上下文一致即可解决问题。

主线程:

RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();.

线程:

RequestContextHolder.setRequestAttributes(requestAttributes );

你可能感兴趣的:(java,feign,java)