gateway构建在Spring5、SpringBoot2和Reactor基础之上。
前言
Spring Cloud
中集成了很多常用的功能,如服务、降级和熔断等,如果要集成Spring Cloud
的功能,首先要注意的就是版本问题:
Spring Cloud和Spring Boot的版本对应表
Cloud版本 | Boot版本 | 描述 |
---|---|---|
2021.0.x aka Jubilee | 2.6.x | |
2020.0.x aka Ilford | 2.4.x, 2.5.x (Starting with 2020.0.3) | |
Hoxton | 2.2.x, 2.3.x (Starting with SR5) | |
Greenwich | 2.1.x | 不再支持 |
Finchley | 2.0.x | 不再支持 |
Edgware | 1.5.x | 不再支持 |
Dalston | 1.5.x | 不再支持 |
使用Spring Cloud Gateway
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
如果想禁用
Gateway
,可使用spring.cloud.gateway.enabled=false
基本组件
Route
: 路由,一个完整的Route由id、uri、predicates和filters构成,当predicates匹配当前请求时,该Route生效;Predicate
: 谓词,判断某个请求是否命中该Route,是一个参数为Spring Framework ServerWebExchange
的类型 Java 8 Function Predicate;Filter
: 当匹配到Route后,这些过滤器将应用到当前请求,执行顺序用Ordered
控制。
工作流程
Gateway Client
发起一个请求;- 如果
Gateway Handler Mapping
匹配当前请求,会转发到Gateway Web Handler
进行处理; Gateway Web Handler
会按顺序执行filters
,并把结果向上返回;
filters
分pre
和post
,其中pre
在实际业务服务之前执行,post
是在实际业务服务之后执行。
注意事项
Gateway
是构建在Spring Boot 2.x、Spring
webflux和Reactor之上,这就意味着和我们常用的Spring-boot-starter-web
并不兼容,所以像Spring data
、Spring Security
等组件也不兼容。
谓词 Predicate
Predicate
:谓词,用于判断当前请求是否命中该Route
定义方式
定义谓词有两种方式:完整定义和快捷定义。
完整定义
spring:
cloud:
gateway:
routes:
- id: after_route
uri: https://imdony.org
predicates:
- name: Cookie
args:
name: mycookie
regexp: mycookievalue
predicates
是一个数组,包括两个key:name
和args
,name
表示该predicate的类型(即采用哪种匹配策略,示例中表示判断Cookie),args
是判断的参数,是一个key-value映射表(示例中表示要包括Cookie键值是mycookie=mycookievalue
才会命中该Route。
快捷定义
spring:
cloud:
gateway:
routes:
- id: after_route
uri: https://example.org
predicates:
- Cookie=mycookie,mycookievalue
快捷方式省略了
name
和args
两个key,直接用name=args
的方式把两部分连接起来,其中args
部分第一个表示args
中的name
,逗号(,
)后面表示regexp
。
预置的Predicate
Spring Cloud Gateway
预置了很多可以直接使用的Predicate
,而且可以组合使用。
After:在某个时间点(ZonedDateTime)之后的请求会命中该Route
spring:
cloud:
gateway:
routes:
- id: after_route
uri: https://imdony.org
predicates:
- After=2017-01-20T17:42:47[Asia/Shanghai]
2017-01-20 17:42:47
之后所有的请求,都将转调https://imdony.org
,可用于控制规划新服务上线时间。
Before:在某个时间点(ZonedDateTime)之前的请求会命中该Route
spring:
cloud:
gateway:
routes:
- id: before_route
uri: https://example.org
predicates:
- Before=2017-01-20T17:42:47[Asia/Shanghai]
2017-01-20 17:42:47
之前所有的请求,都将转调https://imdony.org
,可用于控制服务下线时间。
Between:在某时间之间的请求会命中该Route
spring:
cloud:
gateway:
routes:
- id: between_route
uri: https://example.org
predicates:
- Between=2017-01-20T17:42:47[Asia/Shanghai], 2017-01-21T17:42:47[Asia/Shanghai]
2017-01-20 17:42:47
和2017-01-21 17:42:47
之间所有的请求,都将转调https://imdony.org
,可用于控制