zoukankan      html  css  js  c++  java
  • 我爱java系列---【微服务中feign拦截器的使用】

    1.为什么要用feign拦截器?

     作用:由于服务整合了oauth2,在被调用时需要传递令牌才能正常调用,feign拦截器的作用就是为了在服务之间传递令牌。

    2.feign拦截器怎么用?

    (1)创建拦截器(一般定义在全局中)

    在changgou_common服务中创建一个com.changgou.interceptor.FeignInterceptor拦截器,并将所有头文件数据再次加入到Feign请求的微服务头文件中,代码如下:

    @Component
    public class FeignInterceptor implements RequestInterceptor {
    
        @Override
        public void apply(RequestTemplate requestTemplate) {
    
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    
            if (requestAttributes!=null){
    
                HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
                if (request!=null){
                    Enumeration<String> headerNames = request.getHeaderNames();
                    if (headerNames!=null){
                        while (headerNames.hasMoreElements()){
                            String headerName = headerNames.nextElement();
                            if (headerName.equals("authorization")){
                                String headerValue = request.getHeader(headerName);//Bearer jwt
                                requestTemplate.header(headerName,headerValue);//向下传递令牌
                            }
                        }
                    }
                }
            }
            }
    }

    2) 更改changgou_order_web启动类,添加拦截器声明

    @Bean
    public FeignInterceptor feignInterceptor(){
        return new FeignInterceptor();
    }
    愿你走出半生,归来仍是少年!
  • 相关阅读:
    谈谈近两年维护的一个最最坑爹项目
    LintCode 丑数
    nova 配置文件
    python 网络编程
    python
    python
    cocos2d-js导弹跟踪算法(一边追着目标移动一边旋转角度)
    nginx和apache
    Service绑定模式
    类对象作为成员
  • 原文地址:https://www.cnblogs.com/hujunwei/p/11442463.html
Copyright © 2011-2022 走看看