• Zuul Pre和Post过滤器


    一、项目架构图

    二、前置过滤器

    @Component
    public class TokenFilter  extends ZuulFilter{
        @Override
        public String filterType() {
            return PRE_TYPE;
        }
    
        @Override
        public int filterOrder() {
            return PRE_DECORATION_FILTER_ORDER - 1;
        }
    
        @Override
        public boolean shouldFilter() {
            return true;
        }
    
        @Override
        public Object run() throws ZuulException {
            RequestContext requestContext = RequestContext.getCurrentContext();
            HttpServletRequest request =  requestContext.getRequest();
    
            //这里从url参数获取,也可以从cookie,header里获取
            String token = request.getParameter("token");
            if(StringUtils.isEmpty(token)){
                //不通过
                requestContext.setSendZuulResponse(false);
                requestContext.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
            }
            return null;
        }
    }
    

      

    带了token就能正常访问

    否则,无法访问,返回401

    三、后置过滤器

    1、增加后置过滤器

    @Component
    public class AddResponseHeaderFilter extends ZuulFilter {
        @Override
        public String filterType() {
            return POST_TYPE;
        }
    
        @Override
        public int filterOrder() {
            return SEND_RESPONSE_FILTER_ORDER - 1;
        }
    
        @Override
        public boolean shouldFilter() {
            return true;
        }
    
        @Override
        public Object run() throws ZuulException {
            RequestContext requestContext = RequestContext.getCurrentContext();
           HttpServletResponse response = requestContext.getResponse();
           response.setHeader("X-Foo", UUID.randomUUID().toString());
            return null;
        }
    }
    

      在回复后里增加X-Foo,值为UUID

    2、查看结果

  • 相关阅读:
    iOS ARC下命名规则
    performSelector may cause a leak because its selector is unknown
    performSelector may cause a leak because its selector is unknown
    Block的Retain Cycle的解决方法
    Block的Retain Cycle的解决方法
    iOS 5 ARC 入门
    iOS 5 ARC 入门
    Xcode 5 SVN配置
    Python基本语法_基本数据类型_序列类型详解
    Python基本语法_基本数据类型_序列类型详解
  • 原文地址:https://www.cnblogs.com/linlf03/p/10388973.html
Copyright © 2020-2023  润新知