Spring Cloud Gateway是基于Spring Boot 2.x,Spring WebFlux和Project Reactor 构建的。属于异步非阻塞架构
Spring Cloud Gateway与Spring Data 和Spring Securit 技术不能同时使用
Spring Cloud Gateway基于Spring Boot和Spring Webflux提供的Netty运行。它在传统的Servlet容器中或用WAR的方式构建时不起作用
网关基本的功能 :鉴权、流量控制、熔断、路径重写、⽇志监控等
GateWay核心概念
-
路由(route): 网关最基础的部分,也是网关比较基础的工作单元。
路由由一个ID、一个目标 URL(最终路由到的地址)、一系列的断言(匹配条件判断)和Filter过滤器(精细化控制)组成。
如果断言为true,则匹配该路由。 -
断言(predicates):参考了Java8中的断言java.util.function.Predicate
开发人员可以匹配Http 请求中的所有内容(包括请求头、请求参数等)(类似于Nginx中的location匹配一样)
如果断言与请求相匹配则路由。 -
过滤器(filter):⼀个标准的Spring webFilter,使用过滤器,可以在请求之前或者之后执行业务逻辑。
GateWay工作过程
解释:
客户端向Spring Cloud GateWay发出请求,然后在GateWay Handler Mapping中找到与请求相匹配的路由,将其发送到GateWay Web Handler;
Handler再通过指定的过滤器链来将请求发送到我们实际的服务执行业务逻辑,然后返回。
过滤器之间用虚线分开是因为过滤器可能会在发送代理请求之前(pre)或者之后(post)执行业务逻辑。
Filter在“pre”类型过滤器中可以做参数校验、权限校验、流量监控、日志输出、协议转换等;
在“post”类型的过滤器中可以做响应内容、响应头的修改、日志的输出、流量监控等。
GateWay应用
GateWay不需要使用web模块,它引入的是WebFlux(类似于SpringMVC)
<!--GateWay ⽹关-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!--引⼊webflux-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
application.yml
server:
port: 88
spring:
application:
name: payment-gateway
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
gateway:
routes: # 路由可以有多个
##产品服务路由器,拦截/api/product请求,并重写url地址
- id: product_route # ⾃定义的路由 ID,保持唯⼀
uri: lb://payment-product # ⽬标服务地址 lb表是负载均衡,payment-product 服务名
predicates: # 断言
- Path=/api/product/**
filters: # 过滤器
- RewritePath=/api/(?<segment>/?.*), /$\{
segment}
GateWay断言详解
Spring Cloud GateWay 帮我们内置了很多 Predicates功能,实现了各种路由匹配规则
时间点后匹配 :
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:
gateway:
routes:
- id: before_route
uri: https://example.org
predicates:
- Before=2017-01-20T17:42:47.789-07:00[America/Denver]
时间区间匹配 :
spring:
cloud:
gateway:
routes:
- id: between_route
uri: http