Spring Cloud Gateway 網關非常實用的八個開發(fā)技巧,太實用了
環(huán)境:SpringBoot2.7.18 + SpringCloud Gateway2021.0.7
1. 簡介
Spring Cloud Gateway是Spring Cloud生態(tài)系統中的官方API網關解決方案,它構建在Spring Framework 5、Spring Boot以及Project Reactor之上,旨在為微服務架構提供動態(tài)路由、監(jiān)控、彈性、請求限流、路徑重寫、過濾等功能。作為Zuul的替代方案,Spring Cloud Gateway具備非阻塞、異步的特性,能夠處理高并發(fā)的請求。
Spring Cloud Gateway提供了靈活的網關解決方案,允許開發(fā)者通過簡單的配置實現路由、負載均衡、安全認證、限流、監(jiān)控和日志等功能。它支持多種路由策略,包括基于路徑、請求參數、請求頭、主機等的路由,并預置了許多常用的過濾器,如請求限流、熔斷器等,也支持自定義過濾器。
Spring Cloud Gateway基于Actuator提供了一些非常實用的API幫助管理API接口。引入Actuator依賴后就可以直接使用
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
2. 實戰(zhàn)案例
2.1 查看路由詳細信息
Spring Cloud Gateway添加了一種新的、更詳細的格式。它為每個路由添加了更多的細節(jié),讓你可以查看與每個路由關聯的謂詞和過濾器以及任何可用的配置。接口/actuator/gateway/route的示例如下:
[
{
"predicate": "Paths: [/cloud-gateway/**], match trailing slash: true",
"metadata": {
"nacos.instanceId": null,
"nacos.weight": "1.0",
"nacos.cluster": "DEFAULT",
"nacos.ephemeral": "true",
"nacos.healthy": "true",
"management.port": "8188",
"preserved.register.source": "SPRING_CLOUD"
},
"route_id": "ReactiveCompositeDiscoveryClient_cloud-gateway",
"filters": [
"[[StripPrefix parts = 1], order = 1]",
"[[RewritePath /cloud-gateway/?(?<remaining>.*) = '/${remaining}'], order = 1]"
],
"uri": "lb://cloud-gateway",
"order": 0
},
...
]
通過如下配置可以關閉此功能
spring:
cloud:
gateway:
actuator:
verbose:
enabled: false
2.2 全局過濾器查看
要查看應用于路由的全局過濾器,通過接口/actuator/gateway/globalfilters以 GET方式請求。示例如下:
{
"org.springframework.cloud.gateway.filter.WebsocketRoutingFilter@1d1deb11": 2147483646,
"org.springframework.cloud.gateway.filter.ReactiveLoadBalancerClientFilter@221961af": 10150,
"org.springframework.cloud.gateway.filter.ForwardRoutingFilter@1cfb7450": 2147483647,
"org.springframework.cloud.gateway.filter.RemoveCachedBodyFilter@1e288c76": -2147483648,
"org.springframework.cloud.gateway.filter.RouteToRequestUrlFilter@738ed8f5": 10000,
"org.springframework.cloud.gateway.filter.GatewayMetricsFilter@18d1d137": 0,
"com.pack.common.filters.SecondFilter@38874eb5": 0,
"com.pack.gray.loadbalancer.GrayReactiveLoadBalancerClientFilter@76b019c4": 10150,
"org.springframework.cloud.gateway.filter.AdaptCachedBodyGlobalFilter@41463c56": -2147482648,
"org.springframework.cloud.gateway.filter.LoadBalancerServiceInstanceCookieFilter@32ddcca": 10151,
"org.springframework.cloud.gateway.filter.NettyRoutingFilter@1ddc8fc": 2147483647,
"com.pack.common.filters.BrushProofFilter@55202ba6": -2,
"org.springframework.cloud.gateway.filter.NettyWriteResponseFilter@77d58f3a": -1,
"com.pack.common.filters.FirstFilter@2ef1fc8a": 1,
"org.springframework.cloud.gateway.filter.ForwardPathFilter@478c84aa": 0
}
每一個過濾器后的數字是該過濾器的執(zhí)行順序,值越小,越先執(zhí)行。
2.3 路由過濾器
要獲取應用在路由上的GatewayFilter工廠,通過接口/actuator/gateway/routefilters 以GET方式請求,示例如下:
圖片
以上包括了系統默認的及自定義的網關過濾器工廠【CustomGatewayFilterFactory】。
2.4 路由刷新
要清除路由緩存,通過接口/executor/gateway/refresh 以POST方式請求。該請求返回一個沒有響應體的200。
圖片
當首次訪問路由時會通過RouteLocator進行路由的查找,而這個具體實現是通過CachingRouteLocator進行查找路由,查找到路由以后會將其緩存在Map集合中。該RouteLocator是個監(jiān)聽程序,會監(jiān)聽RefreshRoutesEvent事件,當收到該事件后會重新獲取路由進行緩存。
2.5 獲取定義的路由
要獲取網關中定義的路由,通過接口/executor/gateway/routes以GET方式請求。
[
{
"predicate": "Paths: [/cloud-gateway/**], match trailing slash: true",
"metadata": {
"nacos.instanceId": null,
"nacos.weight": "1.0",
"nacos.cluster": "DEFAULT",
"nacos.ephemeral": "true",
"nacos.healthy": "true",
"management.port": "8188",
"preserved.register.source": "SPRING_CLOUD"
},
"route_id": "ReactiveCompositeDiscoveryClient_cloud-gateway",
"filters": [
"[[StripPrefix parts = 1], order = 1]",
"[[RewritePath /cloud-gateway/?(?<remaining>.*) = '/${remaining}'], order = 1]"
],
"uri": "lb://cloud-gateway",
"order": 0
},
...
]
字段說明:
屬性 | 類型 | 描述 |
route_id | String | 路由id |
route_object.predicate | Object | 路由謂詞 |
route_object.filters | Array | 應用于路由的 GatewayFilter 工廠 |
order | Number | 路由順序 |
2.6 獲取特定路由信息
要獲取單個路由的信息,通過接口 /actuator/gateway/routes/{id}(例如,/actuator/gateway/routes/first_route)以GET方式請求。示例如下:
圖片
字段說明:
屬性 | 類型 | 描述 |
id | String | 路由ID |
predicates | Array | 路由謂詞集合。每項都定義了給定謂詞的名稱和參數 |
filters | Array | 應用于路線的過濾器集合 |
uri | String | 路由的目標 URI |
order | Number | 路由順序 |
2.7 創(chuàng)建&刪除路由
要創(chuàng)建路由,通過接口/gateway/routes/{id_route_to_create}以POST方式請求,請求內容為指定路由字段的 JSON 格式(請參閱 2.6)。
要刪除路由,通過接口 /gateway/routes/{id_route_too_delete}以DELETE方式請求。
創(chuàng)建路由
圖片
查詢創(chuàng)建的路由
圖片
注意:默認創(chuàng)建的路由是存儲在內存中的,重啟服務后就沒有了。
刪除路由
2.8 路由共享
Spring Cloud Gateway 提供兩種 RouteDefinitionRepository 實現。第一種是 InMemoryRouteDefinitionRepository,它只存在于一個網關實例的內存中。這種類型的存儲庫不適合在多個網關實例中填充路由。
為了在 Spring Cloud Gateway 實例集群中共享路由,可以使用 RedisRouteDefinitionRepository。要啟用此類存儲庫,必須將以下屬性設置為 true:spring.cloud.gateway.redis-route-definition-repository.enabled 與 RedisRateLimiter 篩選器工廠一樣,它也需要使用 spring-boot-starter-data-redis-reactive 。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
開啟Redis存儲功能
spring:
cloud:
gateway:
redis-route-definition-repository:
enabled: true