發布時間:2024-01-24閱讀(14)
Spring Cloud Gateway是Spring官方基于Spring 5.0,Spring Boot 2.0和Project Reactor等技術開發的網關,Spring Cloud Gateway旨在為微服務架構提供一種簡單而有效的統一的API路由管理方式。Spring Cloud Gateway作為Spring Cloud生態系中的網關,目標是替代Netflix ZUUL,其不僅提供統一的路由方式,并且基于filter鏈的方式提供了網關基本的功能,例如:安全,監控/埋點,和限流等。
Spring Cloud Gateway的特征使用過Zuul的人,都知道網關的核心肯定是Filter以及Filter Chain(Filter 責任鏈)。Spring Cloud Gateway也具有路由和Filter的概念。下面介紹一下Spring Cloud Gateway中的幾個重要概念。
Spring Cloud Gateway 核心處理流程如下所示。
Gateway的客戶端向Spring Cloud Gateway發起請求,請求首先會被 Gateway Handler Mapping 接收,決定請求匹配的路由,然后發送給Gateway Web Handler。Handler 通過特定的請求filter鏈發送請求。
過濾鏈通過虛線分隔的原因是過濾器filter可以在代理請求發送之前或者之后執行邏輯。執行所有 pre 過濾邏輯,然后發出請求給代理服務(proxied service),之后將執行 post 過濾器邏輯。

將如下依賴項添加到Spring Cloud項目的pom.xml文件中。
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--Spring Cloud Gateway的Starter-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
</dependencies>
Spring Cloud Gateway提供了一個gateway actuator,該EndPoint 提供了關于Filter和Routes的信息查詢。可以在application.yml 中配置開啟。
訪問gateway 端點:
http://localhost:8080/actuator/gateway/routes
可以看到返回的路由信息:
Spring Cloud Gateway網關路由方式
新的gateway網關路由配置有兩種方式:
1.通過@Bean自定義RouteLocator,在啟動主類Application中配置。
2.在配置文件yml中配置。
這兩種方式都可以實現網關路由是等價的,但是通常項目開發中會使用配置文件yml方式。
相關鏈接:
https://cloud.spring.io/spring-cloud-gateway/spring-cloud-gateway.html
Copyright ? 2024 有趣生活 All Rights Reserve吉ICP備19000289號-5 TXT地圖HTML地圖XML地圖