Feign远程调用丢失请求头原因,及解决办法

1.为什么会丢请求头

订单服务 远程调用 购物车服务

  • 订单服务发送请求,是浏览器发起的,会自动带cookie,feign调用购物车的接口,是后端发起的,底层会创建一个新的请求,而这个请求没有任何请求头,原来请求头里的信息都会丢失
  • 解决办法:feign调用远程接口时,会扫描所有的拦截器,执行apply方法,我们可以创建一个拦截器放到spring容器中,在拦截器里把原来的头都放到新创建的请求里

在这里插入图片描述

2.创建拦截器,把原请求的头放到新请求里


@Configuration
public class GuliFeignConfig {

    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor() {

        RequestInterceptor requestInterceptor = new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                //1、使用RequestContextHolder拿到刚进来的请求数据
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

                if (requestAttributes != null) {
                    //老请求
                    HttpServletRequest request = requestAttributes.getRequest();

                    if (request != null) {
                        //2、同步请求头的数据(主要是cookie)
                        //把老请求的cookie值放到新请求上来,进行一个同步
                        String cookie = request.getHeader("Cookie");
                        template.header("Cookie", cookie);
                    }
                }
            }
        };

        return requestInterceptor;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值