时间匹配
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/**