Spring Cloud Gateway使用说明(1)--路由

    2.2.3.RELEASE

本项目提供了一个建立在Spring Ecosystem之上的API网关,包括:Spring 5,Spring Boot 2和Project Reactor。Spring Cloud Gateway旨在提供一种简单而有效的方式来对API进行路由,并提供 安全性、监控/指标 和弹性 相关的切面。

Spring Cloud Gateway 2.2.3 官方使用说明(1)--路由

Spring Cloud Gateway 2.2.3 官方使用说明(2)-- 路由filter(上)

Spring Cloud Gateway 2.2.3 官方使用说明(2)-- 路由filter(下)

Spring Cloud Gateway 2.2.3 官方使用说明(3)-- Global filter

Spring Cloud Gateway 2.2.3 官方使用说明(4)-- HttpHeader Filters

Spring Cloud Gateway 2.2.3 使用说明(5)-- TLS 和 SSL

Spring Cloud Gateway 2.2.3 使用说明(6)-- 其它配置

Spring Cloud Gateway 2.2.3 使用说明(7)-- actuator

Spring Cloud Gateway 2.2.3 使用说明(8)-- 开发指导

 

1. 如何引用Spring Cloud Gateway

要在项目中引入Spring Cloud Gateway,需要引用 group org.springframework.cloud 和 artifact id为spring-cloud-starter-gateway 的 starter。最新的Spring Cloud Release 构建信息,请参阅Spring Cloud Project page

如果应用了该starter,但由于某种原因不希望启用网关,请进行设置

spring.cloud.gateway.enabled=false

注意

Spring Cloud Gateway 是建立在  Spring Boot 2.x,Spring WebFlux 和Project Reactor上的。
因此,很多之前同步的库(如Spring Data 和 Spring Sceurity)和开发模式在Spring Cloud Gateway里会不再适用。
如果你不熟悉上面的项目,我们建议你先去读一下对应的项目文档
重要
Spring Cloud Gateway依赖Spring Boot和Spring Webflux提供的Netty runtime。
它不能在传统的Servlet容器中工作或构建为WAR

2. 词汇表

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

3. 如何工作的

     下图从顶层设计解译介绍Spring Cloud Gateway的工作原理:

客户端发送请求到Spring Cloud Gateway。如果Gateway Handler Mapping 检查请求匹配到一个路由,就会把请求转发到Gateway Web Handler。该请求会经过一系列的Filter处理,先执行所有“pre filter”逻辑,然后进行请求代理。在请求代理执行完后,执行“post filter”逻辑。

提示

如果路由中的uris没有指定端口,则http使用默认端口80, https使用默认端口443

4. 配置路由断言和Filter

有两个方法配置断言和Filter:简化和完整展开参数模式。下面的例子大都使用简化模式配置。

4.1 简化配置

简化配置以Filter名称开头, 然后是 “=”分隔,最后是参数值,多个参数值用“,"分隔。

application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: after_route
        uri: https://example.org
        predicates:
        - Cookie=mycookie,mycookievalue

4.2 完整展开参数

完整展开参数模式很像标准的由键值对组成的yaml配置。那里必然会有一个“name”键和一个“args”键。“args”键保存了断言或filter的一系列属性键值对。

application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: after_route
        uri: https://example.org
        predicates:
        - name: Cookie
          args:
            name: mycookie
            regexp: mycookievalue

这个完整配置和4.1的简化配置效果是一样的。

5. 路由断言

Spring Cloud Gateway将路由作为Spring WebFlux HandlerMapping基础结构的一部分进行匹配。Spring Cloud Gateway包含许多内置的路由断言Factories。这些断言都匹配HTTP请求的不同属性。多个路由断言Factories可以通过 and 组合使用。

5.1 After 路由断言

After Route Predicate Factory采用一个参数——日期时间。在该日期时间之后发生的请求都将被匹配。如下:

Example 1. application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: after_route
        uri: https://example.org
        predicates:
        - After=2017-01-20T17:42:47.789-07:00[America/Denver]

这个路由配置匹配所有美国山区时间2017-01-20 17:42:47后的所有请求

5.2 Before 路由断言

Before Route Predicate Factory采用一个参数——日期时间。在该日期时间之前发生的请求都将被匹配。

Example 2. application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: before_route
        uri: https://example.org
        predicates:
        - Before=2017-01-20T17:42:47.789-07:00[America/Denver]

这个路由配置匹配所有美国山区时间2017-01-20 17:42:47前的所有请求

5.3 Between 路由断言

Between 路由断言 Factory有两个参数,datetime1和datetime2。在datetime1和datetime2之间的请求将被匹配。datetime2参数的实际时间必须在datetime1之后。

Example 3. application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: between_route
        uri: https://example.org
        predicates:
        - Between=2017-01-20T17:42:47.789-07:00[America/Denver], 2017-01-21T17:42:47.789-07:00[America/Denver]

5.4 Cookie 路由断言

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

Example 4. application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: cookie_route
        uri: https://example.org
        predicates:
        - Cookie=chocolate, ch.p

此路由会匹配到包含名称为“chocolate",且值匹配正则表达式“ch.p"的cookie的请求。

5.5 Header 路由断言

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

Example 5. application.yml

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

如果一个请求中包含header 名为"X-Request-Id", 值匹配正则表达式"\d+"(一个或多个数字),则会被匹配到。

5.6 Host 路由断言

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

Example 6. application.yml

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

请求中有“host" header, 并且值为“www.somehost.org” 或 “beta.somehost.org” 或 “www.anotherhost.org” 会被匹配到。

URI模板变量(如{sub}.myhost.org)也是支持的。

URI模板变量(如{sub})保存在ServerWebExchange.getAttributes()中,key为ServerWebExchangeUtils.URI_TEMPLATE_VARIABLES_ATTRIBUTE,类型为map,里面的所有参数都可以在GatewayFilter factories中使用

 

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

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

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

 

5.7 Method 路由断言

Method 路由断言 Factory只包含一个参数: 需要匹配的HTTP请求方式

Example 7. application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: method_route
        uri: https://example.org
        predicates:
        - Method=GET,POST

5.8 Path 路由断言

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

Example 8. application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: path_route
        uri: https://example.org
        predicates:
        - Path=/red/{segment},/blue/{segment}

5.9 Query 路由断言

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

Example 9. application.yml

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

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

application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: query_route
        uri: https://example.org
        predicates:
        - Query=red, gree.

如果请求参数里包含red参数,并且值匹配为gree. 表达式,则将会被路由,如:green 和 greet

5.10 RemoteAddr 路由断言

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


Example 10. application.yml

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

5.11 权重路由断言

此断言有两个参数:group 和 weight。权重根据每个分组来计算

Example 11. application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: weight_high
        uri: https://weighthigh.org
        predicates:
        - Weight=group1, 8
      - id: weight_low
        uri: https://weightlow.org
        predicates:
        - Weight=group1, 2

80%的请求会被路由到weighthigh.org , 20%的请求路由到weightlow.org

5.11.1 修改远程地址的解析方式

默认情况下,RemoteAddr 路由断言 Factory使用传入请求中的remote address。如果Spring Cloud Gateway位于代理层后面,则可能与实际客户端IP地址不匹配。

可以通过设置自定义RemoteAddressResolver来自定义解析远程地址的方式。Spring Cloud Gateway网关附带一个非默认远程地址解析程序, XForwardedRemoteAddressResolver,它基于X-Forwarded-For header

XForwardedRemoteAddressResolver 有两个静态构造函数方法,采用不同的方法保证安全:

1. XForwardedRemoteAddressResolver::TrustAll返回一个RemoteAddressResolver,它始终采用X-Forwarded-for头中找到的第一个IP地址。这种方法容易受到欺骗,因为恶意客户端可能会为解析程序“x-forwarded-for”设置初始值。

2. XForwardedRemoteAddressResolver::MaxTrustedIndex获取一个索引,该索引与在Spring Cloud网关前运行的受信任基础设施数量相关。例如,如果SpringCloudGateway只能通过haproxy访问,则应使用值1。如果在访问Spring Cloud Gateway之前需要两个受信任的基础架构跃点,那么应该使用2。

给定以下值:

X-Forwarded-For: 0.0.0.1, 0.0.0.2, 0.0.0.3

下面的 maxTrustedIndex值将生成以下远程地址:

maxTrustedIndexresult

[Integer.MIN_VALUE,0]

(invalid, IllegalArgumentException during initialization)

1

0.0.0.3

2

0.0.0.2

3

0.0.0.1

[4, Integer.MAX_VALUE]

0.0.0.1

Java代码 配置方式:

Example 12. GatewayConfig.java

RemoteAddressResolver resolver = XForwardedRemoteAddressResolver
    .maxTrustedIndex(1);

...

.route("direct-route",
    r -> r.remoteAddr("10.1.1.1", "10.10.1.1/24")
        .uri("https://downstream1")
.route("proxied-route",
    r -> r.remoteAddr(resolver, "10.10.1.1", "10.10.1.1/24")
        .uri("https://downstream2")
)

 

Spring Cloud Gateway 2.2.3 官方使用说明(1)--路由

Spring Cloud Gateway 2.2.3 官方使用说明(2)-- 路由filter(上)

Spring Cloud Gateway 2.2.3 官方使用说明(2)-- 路由filter(下)

Spring Cloud Gateway 2.2.3 官方使用说明(3)-- Global filter

Spring Cloud Gateway 2.2.3 官方使用说明(4)-- HttpHeader Filters

Spring Cloud Gateway 2.2.3 使用说明(5)-- TLS 和 SSL

Spring Cloud Gateway 2.2.3 使用说明(6)-- 其它配置

Spring Cloud Gateway 2.2.3 使用说明(7)-- actuator

Spring Cloud Gateway 2.2.3 使用说明(8)-- 开发指导

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值