openfeign解决远程调用丢失请求头信息,以及异步编排丢失请求头问题

非异步业务流程

browser 发送请求头自动带了cookie ---------(feign调用)----->微服务A----(feign自己创建request,不带任何请求头)-------->加上feign远程调用的请求拦截器(RequestInterceptor)------>微服务B-------(没有请求头,无法获取cookie信息)

处理

@Configuration
public class OrderFeignConfig {

    @Bean("requestInterceptor")
    public  RequestInterceptor requestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                //RequestContextHolder 获取request
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                HttpServletRequest request = requestAttributes.getRequest();
                String cookie = request.getHeader("Cookie");
                //同步请求头,cookie
                requestTemplate.header("Cookie",cookie);
            }
        };
    }
}

异步编排解决openfeign丢失请求头问题

例子

先配置RequestInterceptor的config配置类,设置RequestAttributes参数

//主线程中获取请求信息
//获取request上下文
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
CompletableFuture<Void> adressFuture = CompletableFuture.runAsync(() -> { 
	//共享主线程
    RequestContextHolder.setRequestAttributes(requestAttributes);
    //执行业务
}, executor);

你可能感兴趣的:(springboot,springcloud,java,spring,servlet)