Gateway的路由规则

时间匹配

Spring Cloud Gateway支持设置一个时间,在请求进行转发的时候,可以通过判断在这个时间之前或者之后进行转发。比如我们现在设置只有在2024年3月

9日之后才会路由转发,在这之前不进行转发,我就可以进行如下配置:

erver:
  port: 8083

spring:
  application:
    name: gateway-service
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848

    gateway:
      routes:
        - id: after_route
          uri: https://www.bilibili.com
          predicates:
             - After=2024-03-09T00:00:00+08:00[Asia/Shanghai]
      discovery:
        locator:
          enabled: true

同样的时间配置还有 Before和Between,前者表示只有请求时间在配置的时间之前才会跳转,后者则是在配置的时间的范围内才会执行.

Cookie 匹配
erver:
  port: 8083

spring:
  application:
    name: gateway-service
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848

    gateway:
      routes:
        - id: after_route
          uri: https://www.bilibili.com
          predicates:
            - Cookie=AA,AA
      discovery:
        locator:
          enabled: true

 不带cookies访问或者cookies的name和value和配置的不一致,也不会跳转到指定的uri页面.

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/**

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值