1. 核心概念
路由(Route): 路由是网关最基础的部分,路由信息由ID、目标URI、一组断言和一组过滤器组成,如果断言路由为真,则说明请求的URI和配置匹配。
断言(Predicate): java8中的断言函数。SpringCloud Gateway中的断言函数输入类型是spring5.0框架中的ServerWebExchage。SpringCloud Gateway中的断言函数允许开发者去定义匹配来自于Http Request中的任何信息,比如请求头和参数等。
过滤器(Filter): 一个标准的Spring Web Filter。 Spring Cloud GateWay 中的Filter分为两种类型,分别是Gateway Filter和Global Filter。过滤器将会对请求和响应进行处理。
2. 配置路由规则
1. path路由匹配规则
spring:
application:
name: gateway-server
cloud:
gateway:
# 路由规则
routes:
- id: product-service # 路由ID,唯一,一般为各个服务名称
uri: http://localhost:7070/ #目标URI,路由到微服务的地址
predicates:
- Path=/product/** # 匹配对应的URL请求,将匹配到的请求追加在目标 URI 之后
2. query路由匹配规则
spring:
application:
name: gateway-server
cloud:
gateway:
# 路由规则
routes:
- id: product-service # 路由ID,唯一,一般为各个服务名称
uri: http://localhost:7070/ #目标URI,路由到微服务的地址
predicates:
#- Query=token # 匹配请求参数中包含 token 的请求
- Query=token, abc. # 匹配请求参数中包含 token 并且参数值满足正则表达式 abc.(abc开头,后面匹配任意字符) 的请求
Query=token
Query=token, abc.
3. method路由匹配规则
spring:
application:
name: gateway-server
cloud:
gateway:
# 路由规则
routes:
- id: product-service # 路由ID,唯一,一般为各个服务名称
uri: http://localhost:7070/ #目标URI,路由到微服务的地址
predicates:
- Method=GET # 匹配任意 GET 请求
4. Datetime路由匹配规则
spring:
application:
name: gateway-server
cloud:
gateway:
# 路由规则
routes:
- id: product-service # 路由ID,唯一,一般为各个服务名称
uri: http://localhost:7070/ #目标URI,路由到微服务的地址
predicates:
# 匹配中国上海时间 2021-02-02 20:20:20 之后的请求
- After=2021-02-02T20:20:20.000+08:00[Asia/Shanghai]
#- Before 在某某时间之前的请求 -Between 介于某某时间之间
5. RemoteAddr路由匹配规则
spring:
application:
name: gateway-server
cloud:
gateway:
# 路由规则
routes:
- id: product-service # 路由ID,唯一,一般为各个服务名称
uri: http://localhost:7070/ #目标URI,路由到微服务的地址
predicates:
# 匹配远程地址请求RemoteAddr的请求,0表示子网掩码
- RemoteAddr=192.168.10.1/0
6. Header路由匹配规则
spring:
application:
name: gateway-server
cloud:
gateway:
# 路由规则
routes:
- id: product-service # 路由ID,唯一,一般为各个服务名称
uri: http://localhost:7070/ #目标URI,路由到微服务的地址
predicates:
# 匹配请求头包含X-Request-Id 并且其值匹配正则表达式 \d+(匹配任意数字) 的请求
- Header=X-Request-Id, \d+
Header=X-Request-Id, \d+
网友评论