zoukankan      html  css  js  c++  java
  • spring cloud 服务A调用服务B自定义token消失,记录

    后端:spring cloud

    前端:vue

    场景:前端ajax请求,包装自定义请求头token到后台做验证,首先调用A服务,A服务通过Feign调用B服务发现自定义token没有传到B服务去;

    原因:cloud 服务之间的调用都是基于Feign的,所以我们可以在调用之前做一些事情,在请求头header中添加自定义请求头token

    首先定义一个feign的拦截器,达到在发送请求前认证token的目的'

    定义一个配置类

    @Configuration // 说明该类是配置类
    public class FeignConfiguration {
    
        /**
         * 创建Feign请求拦截器,在发送请求前设置认证的token,各个微服务将token设置到环境变量中来达到通用
         * @return
         */
        @Bean
        public FeignBasicAuthRequestInterceptor basicAuthRequestInterceptor() {
            return new FeignBasicAuthRequestInterceptor();
        }
    
    
    
    
    }
    

      

    FeignBasicAuthRequestInterceptor 实现RequestInterceptor 接口;RequestInterceptor是feign的拦截器,实现里面的apply方法

     public class FeignBasicAuthRequestInterceptor implements RequestInterceptor {
    
            public FeignBasicAuthRequestInterceptor(){
    
            }
    
            @Override
            public void apply(RequestTemplate requestTemplate) {
                RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
                HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
                Enumeration<String> headerNames = request.getHeaderNames();
                if (headerNames != null) {
                    while (headerNames.hasMoreElements()){
                        String name = headerNames.nextElement();
                        Enumeration<String> values = request.getHeaders(name);
                        while (values.hasMoreElements()) {
                            String value = values.nextElement();
                            requestTemplate.header(name, value);
                        }
                    }
                }
            }
        }
    

      

     注意,在改完以上的部分可能还不生效,需要在A服务的yml文件中添加

    hystrix:
      command:
        default:
          execution:
            isolation:
              strategy: SEMAPHORE

    如果B服务还要调用其他的服务C,在B服务的yml文件中也需要加上改配置

    
    
    
  • 相关阅读:
    vi错误terminal too wide解决方法
    怎么重启shell ubuntu
    程序异常退出 却没有产生core文件
    Linux执行shell脚本方式及区别&命令后台运行
    Linux C程序异常退出怎么办——core文件帮你忙
    Linux中生成Core Dump系统异常信息记录文件的教程
    Linux环境下段错误的产生原因及调试方法小结
    Linux core dump file详解
    putty工具常见设置
    Download PuTTY: latest development snapshot
  • 原文地址:https://www.cnblogs.com/wangjinyu/p/10300680.html
Copyright © 2011-2022 走看看