Spring Cloud Gateway的動態路由怎樣做?集成Nacos實現很簡單

  • 2019 年 10 月 21 日
  • 筆記

file

一、說明

網關的核心概念就是路由配置和路由規則,而作為所有請求流量的入口,在實際生產環境中為了保證高可靠和高可用,是盡量要避免重啟的,所以實現動態路由是非常有必要的;本文主要介紹 Spring Cloud Gateway 實現的思路,並且以Nacos為數據源來講解

PS:關於 Spring Cloud Zuul 的動態路由請看文章《Spring Cloud Zuul的動態路由怎樣做?集成Nacos實現很簡單

 

二、實現要點

要實現動態路由只需關注下面4個點

  1. 網關啟動時,動態路由的數據怎樣載入進來
  2. 靜態路由動態路由以那個為準,ps:靜態路由指的是配置文件里寫死的路由配置
  3. 監聽動態路由的數據源變化
  4. 數據有變化時怎樣通知gateway刷新路由

 

三、具體實現

Spring Cloud Gateway 中載入路由資訊分別由以下幾個類負責

  1. PropertiesRouteDefinitionLocator:從配置文件中讀取路由資訊(如YML、Properties等)
  2. RouteDefinitionRepository:從存儲器中讀取路由資訊(如記憶體、配置中心、Redis、MySQL等)
  3. DiscoveryClientRouteDefinitionLocator:從註冊中心中讀取路由資訊(如Nacos、Eurka、Zookeeper等)

 
我們可以通過自定義 RouteDefinitionRepository 的實現類來實現動態路由的目的

 

3.1. 實現動態路由的數據載入

創建一個NacosRouteDefinitionRepository實現類

NacosRouteDefinitionRepository類可查看:NacosRouteDefinitionRepository.java
file

重寫 getRouteDefinitions 方法實現路由資訊的讀取

 
配置Nacos監聽器,監聽路由配置資訊的變化
file

路由變化只需要往 ApplicationEventPublisher 推送一個 RefreshRoutesEvent 事件即刻,gateway會自動監聽該事件並調用 getRouteDefinitions 方法更新路由資訊

 

3.2. 創建配置類

DynamicRouteConfig類可查看:DynamicRouteConfig.java
file

 

3.3. 添加Nacos路由配置

file
新增配置項:

  • 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 端點查看當前路由資訊

file

可以看到 Nacos 里配置的兩條路由資訊

 
完整的Spring Cloud Gateway程式碼請查看
https://gitee.com/zlt2000/microservices-platform/tree/master/zlt-gateway/sc-gateway

 

推薦閱讀

 
掃碼關注有驚喜!

file