天天看點

Spring Cloud Gateway的動态路由怎樣做?內建Nacos實作很簡單

Spring Cloud Gateway的動态路由怎樣做?內建Nacos實作很簡單

一、說明

網關的核心概念就是路由配置和路由規則,而作為所有請求流量的入口,在實際生産環境中為了保證高可靠和高可用,是盡量要避免重新開機的,是以實作動态路由是非常有必要的;本文主要介紹

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. 實作動态路由的資料加載

建立一個

Nacos

RouteDefinitionRepository

實作類

NacosRouteDefinitionRepository類可檢視:

NacosRouteDefinitionRepository.java
Spring Cloud Gateway的動态路由怎樣做?內建Nacos實作很簡單
重寫

getRouteDefinitions

方法實作路由資訊的讀取

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

Spring Cloud Gateway的動态路由怎樣做?內建Nacos實作很簡單
路由變化隻需要往

ApplicationEventPublisher

推送一個

RefreshRoutesEvent

事件即刻,gateway會自動監聽該事件并調用

getRouteDefinitions

方法更新路由資訊

3.2. 建立配置類

DynamicRouteConfig類可檢視:

DynamicRouteConfig.java
Spring Cloud Gateway的動态路由怎樣做?內建Nacos實作很簡單

3.3. 添加

Nacos

路由配置

Spring Cloud Gateway的動态路由怎樣做?內建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

端點檢視目前路由資訊

Spring Cloud Gateway的動态路由怎樣做?內建Nacos實作很簡單
可以看到

Nacos

裡配置的兩條路由資訊

完整的Spring Cloud Gateway代碼請檢視

https://gitee.com/zlt2000/microservices-platform/tree/master/zlt-gateway/sc-gateway

推薦閱讀