SpringCloud Gateway之路由规则

使用Gateway的方式有两种:

  • 在配置文件yml中配置
  • 代码中注入RouteLocator的Bean
    这两种方式是等价的,建议使用yml配置的方式。

项目依赖

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

</dependencies>

因为Gateway使用的是Netty + webflux,所以不需要引入web模块;只要引入spring-cloud-starter-gateway就行了,里面包含了spring-boot-starter-webflux。

yml配置

server:
  port: 8080
spring:
  application:
    name: test-GATEWAY
  cloud:
    gateway:
      routes:
      - id: ecs-route
        uri: lb://test-ECS
        predicates:
        - Path=/ecs/**
      - id: oss-route
        uri: lb://test-OSS
        predicates:
        - Path=/oss/**

routes下面的属性含义如下:

  • id:我们自定义的路由 ID,保持唯一
  • uri:目标服务地址
  • predicates:路由条件,Predicate 接受一个输入参数,返回一个布尔值结果。该属性包含多种默认方法来将 Predicate 组合成其他复杂的逻辑(比如:与,或,非)
    比如我们访问:http://localhost:8080/ecs/test/list之后,predicates会根据Path这个参数传入的值进行匹配,返回true就把/ecs/test/list路由到服务名为test-ECS的接口中。下面我们详细介绍下路由规则。

路由规则

前面我们使用了 predicates 进行了简单Path的条件匹配,其实Spring Cloud Gateway 的功能很强大,帮我们内置了很多 Predicates功能。
在这里插入图片描述
在项目的启动日志中,我们可以看到有很多PredicateFactory。Gateway 是通过Spring WebFlux的HandlerMapping做为底层支持来匹配到转发路由,这些 Predicates 工厂通过不同的HTTP请求参数来匹配,多个 Predicates 工厂可以组合使用。

Predicate简要说明

Predicate 来源于 Java 8,Predicate 接受一个输入参数,返回一个布尔值结果。该接口包含多种默认方法来将 Predicate 组合成其他复杂的逻辑(比如:与,或,非)。

/**
 * Represents a predicate (boolean-valued function) of one argument.
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #test(Object)}.
 *
 * @param <T> the type of the input to the predicate
 *
 * @since 1.8
 */
@FunctionalInterface
public interface Predicate<T> {

    /**
     * Evaluates this predicate on the given argument.
     *
     * @param t the input argument
     * @return {@code true} if the input argument matches the predicate,
     * otherwise {@code false}
     */
    boolean test(T t);

    /**
     * Returns a composed predicate that represents a short-circuiting logical
     * AND of this predicate and another.  When evaluating the composed
     * predicate, if this predicate is {@code false}, then the {@code other}
     * predicate is not evaluated.
     *
     * <p>Any exceptions thrown during evaluation of either predicate are relayed
     * to the caller; if evaluation of this predicate throws an exception, the
     * {@code other} predicate will not be evaluated.
     *
     * @param other a predicate that will be logically-ANDed with this
     *              predicate
     * @return a composed predicate that represents the short-circuiting logical
     * AND of this predicate and the {@code other} predicate
     * @throws NullPointerException if other is null
     */
    default Predicate<T> and(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }

    /**
     * Returns a predicate that represents the logical negation of this
     * predicate.
     *
     * @return a predicate that represents the logical negation of this
     * predicate
     */
    default Predicate<T> negate() {
        return (t) -> !test(t);
    }

    /**
     * Returns a composed predicate that represents a short-circuiting logical
     * OR of this predicate and another.  When evaluating the composed
     * predicate, if this predicate is {@code true}, then the {@code other}
     * predicate is not evaluated.
     *
     * <p>Any exceptions thrown during evaluation of either predicate are relayed
     * to the caller; if evaluation of this predicate throws an exception, the
     * {@code other} predicate will not be evaluated.
     *
     * @param other a predicate that will be logically-ORed with this
     *              predicate
     * @return a composed predicate that represents the short-circuiting logical
     * OR of this predicate and the {@code other} predicate
     * @throws NullPointerException if other is null
     */
    default Predicate<T> or(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) || other.test(t);
    }

    /**
     * Returns a predicate that tests if two arguments are equal according
     * to {@link Objects#equals(Object, Object)}.
     *
     * @param <T> the type of arguments to the predicate
     * @param targetRef the object reference with which to compare for equality,
     *               which may be {@code null}
     * @return a predicate that tests if two arguments are equal according
     * to {@link Objects#equals(Object, Object)}
     */
    static <T> Predicate<T> isEqual(Object targetRef) {
        return (null == targetRef)
                ? Objects::isNull
                : object -> targetRef.equals(object);
    }
}

在 Spring Cloud Gateway 中 Spring 利用 Predicate 的特性实现了各种路由匹配规则,通过 Header、请求参数等不同的条件来作为条件匹配到对应的路由。

下面的一张图(来自网络)总结了 Spring Cloud 内置的几种 Predicate 的实现
在这里插入图片描述
上图对各个工厂的规则进行了列举,直白点讲:Predicate就是为了实现一组匹配规则,方便让请求过来找到对应的 Route 进行处理。下面对各个匹配提交进行介绍:

时间匹配

Spring Cloud Gateway支持设置一个时间,在请求进行转发的时候,可以通过判断在这个时间之前或者之后进行转发。比如我们现在设置只有在2020年1月9日之后才会路由转发,在这之前不进行转发,我就可以进行如下配置:

server:
  port: 8080
spring:
  application:
    name: test-GATEWAY
  cloud:
    gateway:
      routes:
      - id: ecs-route
        uri: lb://test-ECS
        predicates:
        - Path=/ecs/**
        - After=2020-01-09T00:00:00+08:00[Asia/Shanghai]
      - id: oss-route
        uri: lb://test-OSS
        predicates:
        - Path=/oss/**
  • 上面配置了After属性,设置时间,代表在这时间之后才可以匹配;我们设置的是2020-01-09,这里的时间是通过ZonedDateTime来进行时间的对比,ZonedDateTime 是 Java 8 中的日期时间,用于表示带时区的日期与时间信息的类,ZonedDateTime 支持通过时区来设置时间,中国的时区是:Asia/Shanghai。
  • 上面的示例是指,请求路径为/ecs/,且请求时间在 2020年1月9日0点0分0秒之后的所有请求都转发到地址http://test-ECS/ecs/。+08:00是指时间和UTC时间相差八个小时,时间地区为Asia/Shanghai。
  • 添加完路由规则之后,如果当地时间为1月8日访问地址http://localhost:8080/ecs不会转发,如果是1月9日会自动转发到http://test-ECS/ecs/。

我们把上面路由规则中的 After 改为 Before,则会在某个时间之前的请求都进行转发,如下:

server:
  port: 8080
spring:
  application:
    name: test-GATEWAY
  cloud:
    gateway:
      routes:
      - id: ecs-route
        uri: lb://test-ECS
        predicates:
        - Path=/ecs/**
        - Before=2020-01-09T00:00:00+08:00[Asia/Shanghai]
      - id: oss-route
        uri: lb://test-OSS
        predicates:
        - Path=/oss/**

有了时间前与时间后,那么时间之间的Between如下:

server:
  port: 8080
spring:
  application:
    name: test-GATEWAY
  cloud:
    gateway:
      routes:
      - id: ecs-route
        uri: lb://test-ECS
        predicates:
        - Path=/ecs/**
        - Between=2020-01-01T00:00:00+08:00[Asia/Shanghai],2020-01-09T00:00:00+08:00[Asia/Shanghai]
      - id: oss-route
        uri: lb://test-OSS
        predicates:
        - Path=/oss/**

上面的between配置就是说:在两时间之间即可路由转发,不在不可路由转发。

Cookie 匹配

Gateway的Cookie匹配接收两个参数:一个是 Cookie name ,一个是正则表达式。路由规则就是通过获取对应的 Cookie name 值和正则表达式去匹配,如果匹配上就会执行路由,如果没有匹配上则不执行。

server:
  port: 8080
spring:
  application:
    name: test-GATEWAY
  cloud:
    gateway:
      routes:
      - id: ecs-route
        uri: lb://test-ECS
        predicates:
        - Path=/ecs/**
        - Cookie=userCode,sxd782wc
      - id: oss-route
        uri: lb://test-OSS
        predicates:
        - Path=/oss/**

不带cookies访问

curl http://localhost:8080/ecs/test/list

返回404

{"timestamp":"2020-01-09T09:28:45.726+0000","path":"/ecs/test/list","status":404,"error":"Not Found","message":null}

带上cookies访问,且userCode为sxd782wc,则正常返回。

Header 匹配

Header 匹配 和 Cookie 匹配 一样,也是接收两个参数,一个 header 中属性名称和一个正则表达式,这个属性值和正则表达式匹配则执行。

server:
  port: 8080
spring:
  application:
    name: test-GATEWAY
  cloud:
    gateway:
      routes:
      - id: ecs-route
        uri: lb://test-ECS
        predicates:
        - Path=/ecs/**
        - Header=token,^(?!\d+$)[\da-zA-Z]+$
      - id: oss-route
        uri: lb://test-OSS
        predicates:
        - Path=/oss/**

上面的匹配规则,就是请求头要有token属性,并且值必须为数字和字母组合的正则表达式:

curl http://localhost:8080/ecs/test/list -H "token:12gsd29D" 
Host 匹配

Host匹配 接收一组参数,一组匹配的域名列表,这个模板是一个 ant 分隔的模板,用.号作为分隔符。它通过参数中的主机地址作为匹配规则。

server:
  port: 8080
spring:
  application:
    name: test-GATEWAY
  cloud:
    gateway:
      routes:
      - id: ecs-route
        uri: lb://test-ECS
        predicates:
        - Host=**.baidu.com
      - id: oss-route
        uri: lb://test-OSS
        predicates:
        - Path=/oss/**

请求可以匹配上的:

curl http://localhost:8080/ecs/test/list -H "Host: www.baidu.com" 
curl http://localhost:8080/ecs/test/list -H "Host: map.baidu.com"
请求方式匹配

通过请求的方式是 POST、GET、PUT、DELETE 等进行路由。

server:
  port: 8080
spring:
  application:
    name: test-GATEWAY
  cloud:
    gateway:
      routes:
      - id: ecs-route
        uri: lb://test-ECS
        predicates:
        - Method=GET //或者POST,PUT
      - id: oss-route
        uri: lb://test-OSS
        predicates:
        - Path=/oss/**
请求路径匹配

Path匹配 接收一个匹配路径的参数来判断是否走路由。

server:
  port: 8080
spring:
  application:
    name: test-GATEWAY
  cloud:
    gateway:
      routes:
      - id: ecs-route
        uri: lb://test-ECS
        predicates:
        - Path=/ecs/{segment}
      - id: oss-route
        uri: lb://test-OSS
        predicates:
        - Path=/oss/**

如果请求路径符合要求,则此路由将匹配,例如:/ecs/1 或者 /ecs/bar。

请求参数匹配

Query匹配 支持传入两个参数,一个是属性名,一个为属性值,属性值可以是正则表达式。

predicates:
 - Query=token

只有属性名token,表示只要有token参数就行,不管值是什么,即可路由。

predicates:
 - Query=token, \d+

表示不但要有参数名token,值还要是整数才能路由。

请求 ip 地址匹配

通过设置某个 ip 区间号段的请求才会路由,RemoteAddr Route Predicate 接受 cidr 符号(IPv4 或 IPv6 )字符串的列表(最小大小为1),例如 192.168.0.1/16 (其中 192.168.0.1 是 IP 地址,16 是子网掩码)。

predicates:
 - RemoteAddr=192.168.1.1/24

如果请求的远程地址是 192.168.1.11,则此路由将匹配。

组合使用
predicates:
 - Host=**.baidu.com
 - Path=/ecs/test
 - Method=GET
 - Query=token
 - After=2020-01-9T06:06:06+08:00[Asia/Shanghai]

各种 Predicates 同时存在于同一个路由时,请求必须同时满足所有的条件才被这个路由匹配。

欢迎关注我的微信公众号,不定期更新文章和大家一起学习共勉
在这里插入图片描述

  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值