Spring Cloud Gateway总结

1,269 阅读5分钟

1. Spring Cloud Gateway总结

1.1. 引入gateway

在pom加入如下

         <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>

1.2. 关键词

  • Route 路由:gateway的基本构建模块。它由ID、目标URI、断言集合和过滤器集合组成。如果聚合断言结果为真,则匹配到该路由。
  • Predicate 断言:这是一个Java 8 Function Predicate。输入类型是 Spring Framework ServerWebExchange。这允许开发人员可以匹配来自HTTP请求的任何内容,例如Header或参数
  • Filter 过滤器:这些是使用特定工厂构建的 Spring FrameworkGatewayFilter实例。所以可以在返回请求之前或之后修改请求和响应的内容

1.3. 路由断言Factories

这里我只列出我觉得常用的,更多请参考官方文档

1.3.1. Header 路由断言 Factory

Header 路由断言 Factory有两个参数,header名称和正则表达式。请求包含此header名称且正则表达式为真的将会被匹配

spring:
 cloud:
   gateway:
     routes:
     - id: header_route
       uri: http://example.org
       predicates:
       - Header=X-Request-Id, \d+

1.3.2. Host 路由断言 Factory

Host 路由断言 Factory包括一个参数:host name列表。使用Ant路径匹配规则,.作为分隔符

spring:
  cloud:
    gateway:
      routes:
      - id: host_route
        uri: http://example.org
        predicates:
        - Host=**.somehost.org,**.anotherhost.org

1.3.3. Path 路由断言 Factory

Path 路由断言 Factory 有2个参数: 一个Spring PathMatcher表达式列表和可选matchOptionalTrailingSeparator标识

spring:
  cloud:
    gateway:
      routes:
      - id: host_route
        uri: http://example.org
        predicates:
        - Path=/foo/{segment},/bar/{segment}

例如: /foo/1 or /foo/bar or /bar/baz的请求都将被匹配

URI 模板变量 (如上例中的 segment ) 将以Map的方式保存于ServerWebExchange.getAttributes() key为ServerWebExchangeUtils.URI_TEMPLATE_VARIABLES_ATTRIBUTE. 这些值将在GatewayFilter Factories使用

可以使用以下方法来更方便地访问这些变量

Map<String, String> uriVariables = ServerWebExchangeUtils.getPathPredicateVariables(exchange);

String segment = uriVariables.get("segment");

1.3.4. Query 路由断言 Factory

Query 路由断言 Factory 有2个参数: 必选项 param 和可选项 regexp.

spring:
  cloud:
    gateway:
      routes:
      - id: query_route
        uri: http://example.org
        predicates:
        - Query=baz

则包含了请求参数 baz的都将被匹配。

spring:
  cloud:
    gateway:
      routes:
      - id: query_route
        uri: http://example.org
        predicates:
        - Query=foo, ba.

如果请求参数里包含foo参数,并且值匹配为ba. 表达式,则将会被路由,如:bar and baz

1.3.5. RemoteAddr 路由断言 Factory

RemoteAddr 路由断言 Factory的参数为 一个CIDR符号(IPv4或IPv6)字符串的列表,最小值为1,例如192.168.0.1/16(其中192.168.0.1是IP地址并且16是子网掩码

spring:
  cloud:
    gateway:
      routes:
      - id: remoteaddr_route
        uri: http://example.org
        predicates:
        - RemoteAddr=192.168.1.1/24

如果请求的remote address 为 192.168.1.10则将被路由

1.4. GatewayFilter Factories 过滤器

1.4.1. AddRequestHeader GatewayFilter Factory

用来统一添加请求头

spring:
  cloud:
    gateway:
      routes:
      - id: add_request_header_route
        uri: http://example.org
        filters:
        - AddRequestHeader=X-Request-Foo, Bar

对于所有匹配的请求,这将向下游请求的头中添加 x-request-foo:bar header

1.4.2. Hystrix GatewayFilter Factory

Hystrix 是Netflix开源的断路器组件。Hystrix GatewayFilter允许你向网关路由引入断路器,保护你的服务不受级联故障的影响,并允许你在下游故障时提供fallback响应

		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
		</dependency>

Hystrix GatewayFilter Factory 需要一个name参数,即HystrixCommand的名称

spring:
  cloud:
    gateway:
      routes:
      - id: hystrix_route
        uri: http://example.org
        filters:
        - Hystrix=myCommandName

hystrix过滤器还可以接受可选的fallbackUri 参数。目前,仅支持forward: 预设的URI,如果调用fallback,则请求将转发到与URI匹配的控制器

spring:
  cloud:
    gateway:
      routes:
      - id: hystrix_route
        uri: lb://backing-service:8088
        predicates:
        - Path=/consumingserviceendpoint
        filters:
        - name: Hystrix
          args:
            name: fallbackcmd
            fallbackUri: forward:/incaseoffailureusethis
        - RewritePath=/consumingserviceendpoint, /backingserviceendpoint

当调用hystrix fallback时,这将转发到/incaseoffailureusethis uri。注意,这个示例还演示了(可选)通过目标URI上的'lb`前缀,使用Spring Cloud Netflix Ribbon 客户端负载均衡。

主要场景是使用fallbackUri 到网关应用程序中的内部控制器或处理程序。但是,也可以将请求重新路由到外部应用程序中的控制器或处理程序,如

spring:
  cloud:
    gateway:
      routes:
      - id: ingredients
        uri: lb://ingredients
        predicates:
        - Path=//ingredients/**
        filters:
        - name: Hystrix
          args:
            name: fetchIngredients
            fallbackUri: forward:/fallback
      - id: ingredients-fallback
        uri: http://localhost:9994
        predicates:
        - Path=/fallback

在本例中,gateway应用程序中没有 fallback 实现,但是另一个应用程序中有一个接口实现,注册为“http://localhost:9994”。

要为上面的示例路由设置5秒超时,将使用以下配置

hystrix.command.fallbackcmd.execution.isolation.thread.timeoutInMilliseconds: 5000

1.4.3. PrefixPath GatewayFilter Factory

PrefixPath GatewayFilter 只有一个 prefix 参数.

spring:
  cloud:
    gateway:
      routes:
      - id: prefixpath_route
        uri: http://example.org
        filters:
        - PrefixPath=/mypath

这将给所有匹配请求的路径加前缀/mypath。因此,向/hello发送的请求将发送到/mypath/hello

1.4.4. SetPath GatewayFilter Factory

SetPath GatewayFilter Factory 采用 template路径参数。它提供了一种通过允许路径的模板化segments来操作请求路径的简单方法。使用Spring Framework中的URI模板,允许多个匹配segments

spring:
  cloud:
    gateway:
      routes:
      - id: setpath_route
        uri: http://example.org
        predicates:
        - Path=/foo/{segment}
        filters:
        - SetPath=/{segment}

对于一个 /foo/bar请求,在做下游请求前,路径将被设置为/bar

1.4.5. Retry GatewayFilter Factory

Retry GatewayFilter Factory包括 retries, statuses, methods和 series 参数.

  • retries: 应尝试的重试次数
  • statuses: 应该重试的HTTP状态代码,用org.springframework.http.HttpStatus标识
  • methods: 应该重试的HTTP方法,用 org.springframework.http.HttpMethod标识
  • series: 要重试的一系列状态码,用 org.springframework.http.HttpStatus.Series标识
application.yml.

spring:
     cloud:
         gateway:
         routes:
             - id: retry_test
               uri: http://localhost:8080/flakey
             predicates:
                 - Host=*.retry.com
             filters:
                 - name: Retry
             args:
                 retries: 3
                 statuses: BAD_GATEWAY

注意 retry filter 不支持body请求的重试,如通过body的POST 或 PUT请求

1.4.6. RequestSize GatewayFilter Factory

当请求大小大于允许的限制时,RequestSize GatewayFilter Factory可以限制请求不到达下游服务。过滤器以RequestSize作为参数,这是定义请求的允许大小限制(以字节为单位)

spring:
  cloud:
    gateway:
      routes:
      - id: request_size_route
      uri: http://localhost:8080/upload
      predicates:
      - Path=/upload
      filters:
      - name: RequestSize
        args:
          maxSize: 5000000

1.4.7. StripPrefix GatewayFilter Factory

StripPrefix GatewayFilter Factory 包括一个parts参数。 parts参数指示在将请求发送到下游之前,要从请求中去除的路径中的节数

spring:
  cloud:
    gateway:
      routes:
      - id: nameRoot
        uri: http://nameservice
        predicates:
        - Path=/name/**
        filters:
        - StripPrefix=2

当通过网关发出/name/bar/foo请求时,向nameservice发出的请求将是http://nameservice/foo

参考Spring Cloud Gateway 2.1.0 中文官网文档