GateWay不仅提供了统一的路由方式(反向代理)并且基于Filter(定义过滤器对请求过滤,完成一些功能)链的方式提供了网关基本的功能,例如:鉴权、流量控制、熔断、路径重写、日志监控等。
网关在架构中的位置:
GateWay核心概念:
Spring Cloud GateWay天生就是异步非阻塞的,基于Reactor模型(同步非阻塞的I/O多路复用机制)
一个请求—->网关根据一定条件匹配成功后可以将请求转发到指定的服务器地址,在这个过程中可以将进行一些控制(限流、日志、黑白名单)
路由:**网关最基础部分,也是网关比较基础的工作单元。路由由一个ID、一个目标URL(最终路由到的地址)、一系列的断言(匹配条件判断)和Filter过滤器(精细化控制)组成。如果断言为true,就匹配该路由
断言**:参考jdk8中的java.util.function.Predicate,开发人员可以匹配到Http请求中的所有内容(包括请求头、请求参数等)(类似nginx中的location),如果断言与请求匹配则路由
过滤器**:一个标准的SpringwebFilter,使用过滤器,可以在请求之前或者之后执行业务逻辑
GateWay如何工作:
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:
routes:
- id: before_route
uri: https://example.org
predicates:
- Before=2017-01-20T17:42:47.789-07:00[America/Denver]
时间区间匹配:
spring:
cloud:
routes:
- id: between_route
uri: https://example.org
predicates:
- Before=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
GateWay过滤器:
从过滤器声明周期(影响时机点)的角度来说,主要有两个pre和post:
生命周期时机点 | 作用 |
---|---|
pre | 这种过滤器在请求被路由之前调用。我们可利用这种过滤器实现身份验证、在集群中选择 请求的微服务、记录调试信息等。 |
post | 这种过滤器在路由到微服务以后执行。这种过滤器可用来为响应添加标准的 HTTPHeader、收集统计信息和指标、将响应从微服务发送给客户端等。 |
从过滤器类型的角度,Spring Cloud GateWay的过滤器分为GateWayFilter和GlobalFilter两种
过滤器类型 | 影响范围 |
---|---|
GateWayFilter | 应用到单个路由上 |
GlobalFilter | 应用到所有路由上 |