SpringCloud-Zuul实现路由和服务过滤

一、maven配置

 com.wk.sc
    springcloud-demo
    1.0-SNAPSHOT

    
        1.8
        Greenwich.SR1
    

    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.4.RELEASE
        
    

    
         
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-zuul
        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-client
        
    

    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring-cloud.version}
                pom
                import
            
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

二、application.yml配置

server:
  port: 8769
spring:
  application:
    name: service-zuul
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
# 配置路由策略
zuul:
  routes:
    api-a:
      path: /api-a/**   # 路由规则
      serviceId: service-ribbon  # 匹配服务
    api-b:
      path: /api-b/**
      serviceId: service-feign

三、启动类

@EnableZuulProxy //开启路由代理
@EnableEurekaClient
@EnableDiscoveryClient
@SpringBootApplication
public class ServiceZuulApplication {

    public static void main(String[] args) {
        SpringApplication.run(ServiceZuulApplication.class, args);
    }

}

四、路由测试

http://localhost:8769/api-a/hi?name=zhangsan
http://localhost:8769/api-b/hi?name=zhangsan

根据路由策略配置请求不同的服务

五、过滤实现

/**
 * 自定义zuul过滤规则
 *
 */
@Component
public class MyFilter extends ZuulFilter {

    private static final Logger logger = LoggerFactory.getLogger(MyFilter.class);

    /**
     * 定义过滤周期类型
     * 在zuul中定义了4中过滤周期类型:
     * pre:路由前
     * routing:路由时
     * post:路由后
     * error:发生错误时调用
     *
     * @return
     */
    @Override
    public String filterType() {

        return "pre";
    }

    /**
     * 过滤顺序
     *
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 根据条件定义是否需要过滤:
     * true:需要过滤
     * false:不需要
     *
     * @return
     */
    @Override
    public boolean shouldFilter() {
        //需要过滤生效,此处需要返回true
        return true;
    }

    /**
     * 过滤器具体实现,可以结合业务需求进行复杂的实现
     *
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        logger.info("请求信息,方法[{}],URL[{}]", request.getMethod(), request.getRequestURL().toString());
        //模拟token校验
        String token = request.getParameter("token");
        if (token == null || token.length() == 0){
            //token校验失败返回401
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(401);
            try {
                requestContext.getResponse().getWriter().write("token 为空");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            logger.info("校验通过");
        }
        return null;
    }
}


六、过滤测试

http://localhost:8769/api-a/hi?name=zhangsan&token=uuid-123

分别带token和不带token请求查看效果

你可能感兴趣的:(SpringCloud-Zuul实现路由和服务过滤)