介绍

为了解决上述问题,API网关应运而生。Spring Cloud Zuul首先整合eureka,并注册为eureka的一个应用,同时从eureka获取其他应用的实例信息。此外,Zuul本身还有一套过滤机制。

快速入门

1. 搭建一个SpringBoot工程,命名api-gateway

需要引入zuul和eureka-client依赖

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
    </dependencies>

并且在启动类贴上@EnableZuulProxy和@EnableEurekaClient
最后,配置文件添加应用名和端口

spring.application.name=api-gateway
server.port=5555
eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka

2. 配置请求路由

2.1 传统方式(path-url)

# 传统路由1:单实例 zuul.routes.<路由名>.path=/xx与zuul.routes.<路由名>.url=http://xx绑定
zuul.routes.api-a-url.path=/api-a-url/**
zuul.routes.api-a-url.url=http://localhost:5555/
# url方式还支持本地跳转(forward)
zuul.routes.api-b-url.path=/api-b-url/**
zuul.routes.api-b-url.url=forward:/local

验证方式:

  • 访问http://localhost:5555/api-a-url/index会跳转到http://localhost:5555/index
  • 访问http://localhost:5555/api-b-url/hello会跳转到http://localhost:5555/local/hello
# 传统路由2:多实例 zuul.routes.<路由名>.path与zuul.routes.<路由名>.serviceId绑定(需要向注册中心注册)
zuul.routes.api-a.path=/api-a/**
zuul.routes.api-a.serviceId=hello-service
zuul.routes.api-b.path=/api-b/**
zuul.routes.api-b.serviceId=feign-consumer
# 如果是多实例,需要手动维护实例清单
ribbon.eureka.enabled=false
hello-service.ribbon.listOfServers=http://localhost:8081

验证方式

  • 访问http://localhost:5555/api-a/hello会跳转到http://localhost:8081/hello(服务hello-service在8081端口)
  • 访问http://localhost:5555/api-b/hello会跳转到http://localhost:9001/hello(服务feign-consumer在9001端口)

2.2 面向服务

# 服务路由 zuul.routes.<serviceId>=<path>
zuul.routes.hello-service=/api-a/**
zuul.routes.feign-consumer=/api-b/**

验证

  • 访问http://localhost:5555/hello-service/api-a/hello会跳转到http://localhost:8081/hello
  • 访问http://localhost:5555/api-b/feign-consumer会跳转到http://localhost:9001/feign-consumer

2.3 其他配置

  • 忽略表达式
    • zuul.ignored-patterns=/**/hello/**
    • 示例:令含有/hello的接口不被访问(但/hello1可以正常访问)
    • 现象:访问http://localhost:5555/api-a/hello,404
  • 路由前缀(Finchley.SR1正常,已修复bug):zuul.prefix=/api-a
  • Cookie与头信息,登录和鉴权问题(Cookie在SpringCloud Zuul默认不传递)
    • zuul.routes.<router>.custom-sensitive-headers=true
  • 重定向问题,暴露了实例地址,需要设置host头信息:zuul.add-host-header=true
  • Hystrix和Ribbon支持(需要path与serviceId绑定的方式)
    • HystrixCommand执行的超时时间(要大于Ribbon的超时时间才能触发重试)
      • hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=60000
    • 请求连接的超时时间:ribbon.ConnectTimeout=3000
    • 请求处理的超时时间:ribbon.ReadTimeout=60000
    • 关闭重试机制:zuul.retryable=false
  • 自定义映射规则
        /**
         * 自定义路由规则: 微服务名,helloservice-v1 ===>/v1/helloservice/**
         *               相当于zuul.routes.helloservice-v1=/v1/helloservice/**
         * @return
         */
        @Bean
        public PatternServiceRouteMapper serviceRouteMapper() {
            return new PatternServiceRouteMapper(
                    "(?<name>^.+)-(?<version>v.+$)",
                    "${version}/${name}");
        }
    
  • 禁用过滤器
    # 禁用指定类型的自定义拦截器,zuul.<SimpleClassName>.<filterType>.disable=true
    zuul.AccessFilter.pre.disable=true
    

3. 请求过滤

3.1 自定义过滤器示例

  1. 继承ZuulFilter并实现其抽象方法
  2. 指定过滤器类型filterType:pre,route,post,error
  3. 指定过滤器执行顺序filterOrder
  4. 判断过滤器是否需要执行shouldFilter
  5. 在run()实现过滤器的具体逻辑
  6. 使用@component标记该过滤器为Spring组件(或者手动创建)
    【读书笔记】7.API服务网关Spring Cloud Zuul-LMLPHP

3.2 请求生命周期

  • 过滤器类型filterType详解
    • pre,在请求被路由之前调用
    • route,路由请求时调用
    • post,routing和error之后调用,返回给客户端
    • error,处理请求发生错误时调用(上述三个阶段)

核心过滤器源码位于spring-cloud-netflix-zuul依赖的org.springframework.cloud.netflix.zuul.filters包下
【读书笔记】7.API服务网关Spring Cloud Zuul-LMLPHP

  • 异常处理(Brixton.SR5版本,即SpringCloud微服务实战(2017.5 第一版)使用的版本)
    原理:SendErrorFilter的执行顺序是0,是post阶段第一个执行的过滤器,执行的逻辑是上下文是否包含"error.status_code",下面的两种方法利用了此特性
    • 方法1:在run()里使用try-catch,一旦发生异常,在上下文中添加error.*参数,如下
      	public Object run() {
      		try {
      			int i = 1 / 0;
      		} catch(Throwable throwable) {
      			RequestContext ctx = RequestContext.getCurrentContext();
      	        Throwable throwable = ctx.getThrowable();
      	        ctx.set("error.status_code", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      	        ctx.set("error.message", "自定义错误过滤器拦截到内部异常");
      	        ctx.set("error.exception", throwable.getCause());
      		}
              return null;
      }
      
    • 方法2:利用pre,route,post阶段抛异常都会进入error阶段的特性,自定义一个error过滤器统一处理
      @Component
      public class ErrorFilter extends ZuulFilter {
      
          @Override
          public String filterType() {
              return "error";
          }
      
          @Override
          public int filterOrder() {
              return 10;
          }
      
          @Override
          public boolean shouldFilter() {
              return true;
          }
      
          @Override
          public Object run() throws ZuulException {
              // 参考方法1
          }
      }
      
    不足与改进
    方法1适合在各个过滤器中增加try-catch捕获异常,方法2是作为方法1的补充,利用过滤器生命周期的特性,集中处理pre,route,post阶段跑出的异常,一般情况两种同时使用。
    但是,如果post阶段抛出异常,error过滤器捕获后,后续没有post接手,也就没有将请求响应给客户端。
    解决:自定义一个error过滤器并继承SendErrorFilter,并且通过FilterProcessor.setProcessor(new ErrorExtFilter())启动过滤器
    	@Component
    	public class ErrorExtFilter extends SendErrorFilter{
    
    	    @Override
    	    public String filterType() {
    	        return "error";
    	    }
    
    	    @Override
    	    public int filterOrder() {
    	    	//要大于上面ErrorFilter的顺序(10)
    	        return 30;
    	    }
    
    	    @Override
    	    public boolean shouldFilter() {
    	    	 // 仅处理post抛出的异常
    	        RequestContext ctx = RequestContext.getCurrentContext();
    	        ZuulFilter failedFilter = (ZuulFilter) ctx.get("failed.filter");
    	        if (failedFilter != null && failedFilter.filterType().equals("post")) {
    	            return true;
    	        }
    	        return false;
    	    }
    
    	    @Override
    	    public Object run() throws ZuulException {
    	        // 参考方法1
    	    }
    
  • 异常处理(Finchley.SR1版本)
    先来看看SendErrorFilter的源码
    【读书笔记】7.API服务网关Spring Cloud Zuul-LMLPHP
    【读书笔记】7.API服务网关Spring Cloud Zuul-LMLPHP
    显然,往上下文添加error.*的方式不可行了,那么新的方式是怎样的呢?
    在run()一样使用try-catch,但是捕获到异常后,直接抛出异常,后面有过滤器接收;
    同时,post阶段抛出异常的异常,也自动处理了,无需再创建一个error过滤器。
10-04 21:15