zoukankan      html  css  js  c++  java
  • springcloud- FeginClient 调用统一拦截添加请求头 RequestInterceptor ,被调用服务获取请求头

    使用场景:

      在springcloud中通过Fegin调用远端RestApi的时候,经常需要传递一些参数信息到被调用服务中去,比如从A服务调用B服务的时候,
      需要将当前用户信息传递到B调用的服务中去,我们就可以使用实现 RequestInterceptor接口,完成FeginClient 请求调用时拦截请求的统一处理请求头,添加请求头信息等;

    @Slf4j
    @Component
    public class DtsInterceptor implements RequestInterceptor {
    
        @Override
        public void apply(RequestTemplate requestTemplate) {
             //TODO 做一些业务处理,获取数据,添加数据到请求头
             requestTemplate.header(key,value);
        }
    }

     在被调用服务中获取请求头

     第一种方式:

    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    try {
        request.setCharacterEncoding(“UTF-8”);
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }
    String sUserInfo = request.getHeader(KEY);

    第二种方式:

     配置Spring MVC的拦截器(Interceptor),可以自定义实现HandlerInterceptor接口,也可以通过继承HandlerInterceptorAdapter类,后者是前者的实现类。

    public class UserInterceptor extends HandlerInterceptorAdapter {
    
        /** 预处理回调方法,实现处理器的预处理(如登录检查)。
         * 第三个参数为响应的处理器,即controller。
         * 返回true,表示继续流程,调用下一个拦截器或者处理器。
         * 返回false,表示流程中断,通过response产生响应。
         *
         */
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            String key = request.getHeader("key");
            if(StringUtils.isNotBlank(key)){
                return false ;
            }else {
                //TODO 解析key为用户信息,解析成功返回true,解析失败返回false
                return true ;
            }
        }
    
    
        /**
         *当前请求进行处理之后,也就是Controller 方法调用之后执行,
         *但是它会在DispatcherServlet 进行视图返回渲染之前被调用。
         *此时我们可以通过modelAndView对模型数据进行处理或对视图进行处理。
    */
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
            super.postHandle(request, response, handler, modelAndView);
        }
    
        /**
         *方法将在整个请求结束之后,也就是在DispatcherServlet 渲染了对应的视图之后执行。
         *这个方法的主要作用是用于进行资源清理工作的。
         */
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            super.afterCompletion(request, response, handler, ex);
        }
    为了使自定义的拦截器生效,需要注册拦截器到spring容器中,具体的做法是继承WebMvcConfigurerAdapter类,覆盖其addInterceptors(InterceptorRegistry registry)方法。最后别忘了把Bean注册到Spring容器中,可以选择@Component 或者 @Configuration。
    @Component
    public class InterceptorConfiguration extends WebMvcConfigurerAdapter {
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            // 注册拦截器
            InterceptorRegistration interceptorRegistration = registry.addInterceptor(new UserInterceptor());
            // 配置拦截的路径
            interceptorRegistration.addPathPatterns("/**");
            // 配置不拦截的路径
            interceptorRegistration.excludePathPatterns("/**.html");
            // 还可以在这里注册其它的拦截器
            // registry.addInterceptor(new OtherInterceptor()).addPathPatterns("/**");
          super.addInterceptors(registry);
        }
    }
  • 相关阅读:
    sonarqube添加C和C++语言
    sonarqube代码质量分析神器安装和使用
    sonarqube8.8汉化教程
    sonarqube代码分析平台踩坑指南
    解决Windows下PowerShell无法进入Python虚拟环境
    人工智能识别图片入门
    Python深拷贝和浅拷贝解读
    白嫖微软Azure12个月服务器
    Jmeter分布式压测
    Python+Appium实现自动抢微信红包
  • 原文地址:https://www.cnblogs.com/wenq001/p/9132118.html
Copyright © 2011-2022 走看看