1. 程式人生 > 程式設計 >Spring Cloud Gateway的動態路由怎樣做?整合Nacos實現很簡單

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

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","args": {
					"pattern": "/github/**"
			}
		}],"uri": "http://github.com/","filters": []
	}
]
複製程式碼

新增兩條路由資料

 

四、測試

啟動閘道器通過 /actuator/gateway/routes 端點檢視當前路由資訊

file

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

 

完整的Spring Cloud Gateway程式碼請檢視

gitee.com/zlt2000/mic…

 

推薦閱讀

  掃碼關注有驚喜!

file