Spring Cloud Gateway的動態路由怎樣做?整合Nacos實現很簡單
阿新 • • 發佈:2019-12-31
一、說明
閘道器的核心概念就是路由配置和路由規則,而作為所有請求流量的入口,在實際生產環境中為了保證高可靠和高可用,是儘量要避免重啟的,所以實現動態路由是非常有必要的;本文主要介紹 Spring Cloud Gateway
實現的思路,並且以Nacos
為資料來源來講解
PS:關於 Spring Cloud Zuul
的動態路由請看文章《Spring Cloud Zuul的動態路由怎樣做?整合Nacos實現很簡單》
二、實現要點
要實現動態路由只需關注下面4個點
- 閘道器啟動時,
動態路由
的資料怎樣載入進來 -
靜態路由
與動態路由
以那個為準,ps:靜態路由
指的是配置檔案裡寫死的路由配置 - 監聽
動態路由
- 資料有變化時怎樣
通知gateway
重新整理路由
三、具體實現
Spring Cloud Gateway
中載入路由資訊分別由以下幾個類負責
- PropertiesRouteDefinitionLocator:從配置檔案中讀取路由資訊(如YML、Properties等)
- RouteDefinitionRepository:從儲存器中讀取路由資訊(如記憶體、配置中心、Redis、MySQL等)
- DiscoveryClientRouteDefinitionLocator:從註冊中心中讀取路由資訊(如Nacos、Eurka、Zookeeper等)
我們可以通過自定義 RouteDefinitionRepository
3.1. 實現動態路由的資料載入
建立一個Nacos
的RouteDefinitionRepository
實現類
NacosRouteDefinitionRepository類可檢視:NacosRouteDefinitionRepository.java
重寫
getRouteDefinitions
方法實現路由資訊的讀取
配置Nacos監聽器,監聽路由配置資訊的變化
路由變化只需要往
ApplicationEventPublisher
推送一個RefreshRoutesEvent
事件即刻,gateway會自動監聽該事件並呼叫getRouteDefinitions
方法更新路由資訊
3.2. 建立配置類
DynamicRouteConfig類可檢視:DynamicRouteConfig.java
3.3. 新增Nacos
路由配置
新增配置項:
- Data Id:scg-routes
- Group:SCG_GATEWAY
- 配置內容:
[
{
"id": "csdn","predicates": [{
"name": "Path","args": {
"pattern": "/csdn/**"
}
}],"uri": "https://www.csdn.net/","filters": []
},{
"id": "github","args": {
"pattern": "/github/**"
}
}],"uri": "http://github.com/","filters": []
}
]
複製程式碼
新增兩條路由資料
四、測試
啟動閘道器通過 /actuator/gateway/routes
端點檢視當前路由資訊
可以看到
Nacos
裡配置的兩條路由資訊
完整的Spring Cloud Gateway程式碼請檢視
推薦閱讀
- 日誌排查問題困難?分散式日誌鏈路跟蹤來幫你
- zuul整合Sentinel最新的閘道器流控元件
- Spring Cloud Zuul的動態路由怎樣做?整合Nacos實現很簡單
- Spring Cloud開發人員如何解決服務衝突和例項亂竄?
- Spring Cloud同步場景分散式事務怎樣做?試試Seata
- Spring Cloud非同步場景分散式事務怎樣做?試試RocketMQ
掃碼關注有驚喜!