Spring Cloud Gateway的動態路由怎樣做?集成Nacos實現很簡單
- 2019 年 10 月 21 日
- 筆記
一、說明
網關的核心概念就是路由配置和路由規則,而作為所有請求流量的入口,在實際生產環境中為了保證高可靠和高可用,是盡量要避免重啟的,所以實現動態路由是非常有必要的;本文主要介紹 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", "predicates": [{ "name": "Path", "args": { "pattern": "/github/**" } }], "uri": "http://github.com/", "filters": [] } ]
添加兩條路由數據
四、測試
啟動網關通過 /actuator/gateway/routes
端點查看當前路由資訊
可以看到
Nacos
里配置的兩條路由資訊
完整的Spring Cloud Gateway程式碼請查看
https://gitee.com/zlt2000/microservices-platform/tree/master/zlt-gateway/sc-gateway
推薦閱讀
- 日誌排查問題困難?分散式日誌鏈路跟蹤來幫你
- zuul集成Sentinel最新的網關流控組件
- Spring Cloud Zuul的動態路由怎樣做?集成Nacos實現很簡單
- Spring Cloud開發人員如何解決服務衝突和實例亂竄?
- Spring Cloud同步場景分散式事務怎樣做?試試Seata
- Spring Cloud非同步場景分散式事務怎樣做?試試RocketMQ
掃碼關注有驚喜!