GateWay路由规则与动态路由详细介绍

来自:网络
时间:2022-12-30
阅读:
目录

1、路由规则

Spring Cloud GateWay 帮我们内置了很多 Predicates功能,实现了各种路由匹配规则(通过 Header、请求参数等作为条件)匹配到对应的路由。

GateWay路由规则与动态路由详细介绍

时间点后匹配

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

时间点前匹配

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

时间区间匹配

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]

指定Cookie正则匹配指定值

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

指定Header正则匹配指定值

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

请求Host匹配指定值

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

请求Method匹配指定请求方式

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

请求路径正则匹配

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

请求包含某参数

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

请求包含某参数并且参数值匹配正则表达式

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

远程地址匹配

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

2、动态路由

GateWay支持自动从注册中心中获取服务列表并访问,即所谓的动态路由

实现步骤如下

  • pom.xml中添加注册中心客户端依赖(因为要获取注册中心服务列表,eureka客户端已经引入)
  • 动态路由配置

GateWay路由规则与动态路由详细介绍

注意:动态路由设置时,uri以 lb: //开头(lb代表从注册中心获取服务),后面是需要转发到的服务名称

返回顶部
顶部