1、Spring Cloud Gateway 簡介
Spring Cloud Gateway 系列目錄
Spring Cloud Gateway(一):認識Spring Cloud Gateway
Spring Cloud Gateway(二):Spring Cloud Gateway整合Eureka應用
Spring Cloud Gateway(三):網關處理器
Spring Cloud Gateway(四):路由定義定位器 RouteDefinitionLocator
Spring Cloud Gateway(五):路由定位器 RouteLocator
Spring Cloud Gateway(六):路由謂詞工廠 RoutePredicateFactory
Spring Cloud Gateway(七):路由謂詞工廠WeightRoutePredicateFactory
Spring Cloud Gateway(八):其它路由謂詞工廠
Spring Cloud Gateway(九):網關過濾器 GatewayFilter
Spring Cloud Gateway(十):網關過濾器工廠 GatewayFilterFactory
1.1、Spring Cloud Gateway 是什么
Spring Cloud Gateway 基於 Spring Boot 2, 是 Spring Cloud 的 全新 項目, 該項 目 提供 了 一個 構建 在 Spring 生態 之上 的 API 網關, 包括 Spring 5、 Spring Boot 2 和 Project Reactor。 Spring Cloud Gateway 旨在 提供 一種 簡單 而 有效 的 途徑 來 轉發 請求, 並為 它們 提供 橫 切 關注 點, 例如: 安全性、 監控/ 指標 和 彈性。
1.2、Spring Cloud Gateway 特性
- 基於 Java 8 編碼;
- 基於Spring Framework 5,Project Reactor和Spring Boot 2.0構建
- 支持動態路由,能夠匹配任何請求屬性上的路由。
- 支持 內置 到 Spring Handler 映射 中的 路 由 匹配;
- 支持 基於 HTTP 請求 的 路 由 匹配( Path、 Method、 Header、 Host 等);
- 集成了Hystrix斷路器
- 過濾器 作用於 匹配 的 路 由;
- 過濾器可以修改 HTTP 請求和HTTP 響應( 增加/ 修改 頭部、 增加/ 修改 請求 參數、 改寫 請求 路徑 等);
- 支持 Spring Cloud DiscoveryClient 配置路由,與服務發現與注冊配合使用。
- 支持限流
- 支持地址重寫
1.3、Spring Cloud Gateway 詞匯
Route(路由): 路由網關的基本構建塊。 它由ID,目標URI,謂詞集合和過濾器集合定義。 如果聚合謂詞為真,則匹配路由。
Predicate: 這是一個Java 8函數謂詞。 輸入類型是Spring Framework ServerWebExchange。 這允許開發人員匹配HTTP請求中的任何內容,例如標頭或參數。
Filter: 這些是使用特定工廠構建的Spring Framework GatewayFilter實例。 這里,可以在發送下游請求之前或之后修改請求和響應。
2、Spring Cloud Gateway 與 Zuul的區別
在 Finchley 正式版之前,Spring Cloud 推薦的網關是 Netflix 提供的Zuul:
1、Zuul 1.x,是一個基於阻塞 I/ O 的 API Gateway
2、Zuul 1.x 基於Servlet 2. 5,使用阻塞架構,它不支持任何長連接,如 WebSocket。 Zuul 的設計模式和Nginx較像,每次 I/ O 操作都是從工作線程中選擇一個執行,請求線程被阻塞到工作線程完成,但是差別是Nginx 用C++ 實現,Zuul 用 Java 實現,而 JVM 本身會有第一次加載較慢的情況,使得Zuul 的性能相對較差。
3、Zuul 2.x,基於 Netty 非阻塞、支持長連接,但 Spring Cloud 目前還沒有整合。 Zuul 2.x的性能較 Zuul 1.x 有較大提升。在性能方面,根據官方提供的基准測試, Spring Cloud Gateway 的 RPS(每秒請求數)是Zuul 的 1. 6 倍。
4、Spring Cloud Gateway 建立 在 Spring Framework 5、 Project Reactor 和 Spring Boot 2 之上, 使用 非 阻塞 API。
5、Spring Cloud Gateway 還 支持 WebSocket, 並且 與 Spring 緊密 集成, 擁有 更好 的 開發 體驗
3、Spring Cloud Gateway 工作流程

客戶端向 Spring Cloud Gateway 發出請求。然后在 Gateway Handler Mapping 中找到與請求相匹配的路由,將其發送到 Gateway Web Handler。Handler 再通過指定的過濾器鏈來將請求發送到我們實際的服務執行業務邏輯,然后返回。
過濾器之間用虛線分開是因為過濾器可能會在發送代理請求之前(“pre”)或之后(“post”)執行業務邏輯。
4、Spring Cloud Gateway 默認路由規則
路由格式:
http://GATEWAY_HOST:GATEWAY_PORT/UPPER_SERVICEID/**
事例:
http://localhost:9000/EUREKA-CLIENT@192.168.1.101@8000/api/users
- GATEWAY_HOST:網關主機
- GATEWAY_PORT:網關端口
- UPPER_SERVICEID:應用在注冊中心的唯一serviceId,默認大寫訪問,同時serviceId中不要包含【/】
備注: Spring Cloud Gateway需要Spring Boot和Spring Webflux提供的Netty運行時。
它不能在傳統的Servlet容器中工作或構建為WAR。
