zoukankan      html  css  js  c++  java
  • 远程调用丢失请求头与定义RequestInterceptor

    feign远程调用的请求头中没有含有JSESSIONIDcookie,所以也就不能得到服务端的session数据,cart认为没登录,获取不了用户信息

     我们追踪远程调用的源码,可以在SynchronousMethodHandler.targetRequest()方法中看到他会遍历容器中的RequestInterceptor进行封装

    Request targetRequest(RequestTemplate template) {
    for (RequestInterceptor interceptor : requestInterceptors) {
    interceptor.apply(template);
    }
    return target.apply(template);
    }

    根据追踪源码,我们可以知道我们可以通过给容器中注入RequestInterceptor,从而给远程调用转发时带上cookie

    但是在feign的调用过程中,会使用容器中的RequestInterceptor对RequestTemplate进行处理,因此我们可以通过向容器中导入定制的RequestInterceptor为请求加上cookie。

    public class GuliFeignConfig {
    @Bean
    public RequestInterceptor requestInterceptor() {
    return 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信息放到feign请求上
    String cookie = request.getHeader("Cookie");
    template.header("Cookie", cookie);
    }
    }
    }
    };
    }
    }

    注意:上面在封装cookie的时候要拿到原来请求的cookie,设置到新的请求中

    RequestContextHolder为SpingMVC中共享request数据的上下文,底层由ThreadLocal实现,也就是说该请求只对当前访问线程有效,如果new了新线程就找不到原来request了

  • 相关阅读:
    MySQL之汇总数据(AVG,COUNT,MAX,MIN,SUM)
    查询两门及两门以上不及格同学的平均分
    百度乐播音乐真实地址查找api接口
    腾讯云服务器无法ssh登陆问题
    ubuntu搭建php运行环境
    阿里云腾讯云服务器ubuntu多域名配置
    PHP 快速排序算法详解
    PHP7.x新特性
    PHP的钩子实现解析
    PHP 二维数组根据某个字段排序 复制代码 array_multisort
  • 原文地址:https://www.cnblogs.com/vincentmax/p/14582819.html
Copyright © 2011-2022 走看看