最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用Nacos實現(xiàn)動態(tài)路由的步驟和代碼示例

 更新時間:2024年09月05日 08:48:03   作者:威哥愛編程  
這篇文章主要介紹了使用 Nacos 實現(xiàn) Spring Cloud Gateway 的動態(tài)路由,本文給大家介紹了具體的實現(xiàn)步驟和代碼案例,感興趣的小伙伴跟著小編一起來看看吧

最近寫到 使用 Nacos 實現(xiàn)動態(tài)路由的問題,整理了一下思路和案例,分享給大家。

使用 Nacos 實現(xiàn) Spring Cloud Gateway 的動態(tài)路由,主要涉及到以下幾個步驟:

  • 添加依賴:在 Spring Cloud Gateway 應(yīng)用的 pom.xml 文件中添加 Nacos 相關(guān)依賴。

  • 配置 Nacos:在 application.ymlapplication.properties 文件中配置 Nacos 服務(wù)地址。

  • 啟用動態(tài)路由:在配置文件中啟用 Nacos 動態(tài)路由功能。

  • 創(chuàng)建動態(tài)路由配置:在 Nacos 配置中心創(chuàng)建動態(tài)路由的配置信息。

  • 監(jiān)聽配置變化:在 Spring Cloud Gateway 應(yīng)用中監(jiān)聽 Nacos 配置變化,動態(tài)更新路由規(guī)則。

下面是具體的實現(xiàn)步驟和代碼案例,來看一下:

1. 添加依賴

pom.xml 文件中添加 Spring Cloud Gateway 和 Nacos 相關(guān)依賴:

<dependencies>
    <!-- Spring Cloud Gateway -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
    <!-- Spring Cloud Alibaba Nacos Discovery -->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>
    <!-- Spring Cloud Alibaba Nacos Config -->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
    </dependency>
</dependencies>

2. 配置 Nacos

在 application.yml 文件中配置 Nacos 服務(wù)地址:

spring:
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848 # Nacos 服務(wù)地址
      config:
        server-addr: 127.0.0.1:8848 # Nacos 配置中心地址
        file-extension: yml # 配置文件格式
        group: DEFAULT_GROUP # 配置分組
        namespace: # 配置命名空間

3. 啟用動態(tài)路由

在 application.yml 文件中啟用 Nacos 動態(tài)路由功能:

spring:
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true # 開啟從注冊中心動態(tài)創(chuàng)建路由的功能
          lower-case-service-id: true # 使用小寫服務(wù)名,默認(rèn)是大寫

4. 創(chuàng)建動態(tài)路由配置

在 Nacos 配置中心創(chuàng)建一個配置文件,例如 gateway-routes.yml,內(nèi)容如下:

spring:
  cloud:
    gateway:
      routes:
        - id: my-service-route
          uri: lb://MY-SERVICE
          predicates:
            - Path=/my-service/**
          filters:
            - StripPrefix=1

5. 監(jiān)聽配置變化

在 Spring Cloud Gateway 應(yīng)用中,創(chuàng)建一個配置類來監(jiān)聽 Nacos 配置變化,并刷新路由規(guī)則:

import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
public class DynamicRouteService {

    private final RouteDefinitionWriter routeDefinitionWriter;
    private final RouteDefinitionLocator routeDefinitionLocator;

    public DynamicRouteService(RouteDefinitionWriter routeDefinitionWriter,
                                RouteDefinitionLocator routeDefinitionLocator) {
        this.routeDefinitionWriter = routeDefinitionWriter;
        this.routeDefinitionLocator = routeDefinitionLocator;
    }

    @EventListener
    public void onEnvironmentChange(EnvironmentChangeEvent event) {
        if (event.getKeys().contains("spring.cloud.gateway.routes")) {
            routeDefinitionLocator.getRouteDefinitions()
                .subscribe(routeDefinitions -> {
                    routeDefinitionWriter.delete("*").subscribe();
                    routeDefinitionWriter.save(routeDefinitions).subscribe();
                });
        }
    }
}

這個類會監(jiān)聽環(huán)境變化事件,當(dāng)檢測到 spring.cloud.gateway.routes 配置項發(fā)生變化時,會重新加載和刷新路由規(guī)則。

我們通過使用 Nacos 實現(xiàn) Spring Cloud Gateway 的動態(tài)路由。通過在 Nacos 配置中心維護(hù)路由配置,可以實現(xiàn)不重啟網(wǎng)關(guān)服務(wù)的情況下動態(tài)更新路由規(guī)則,這對于微服務(wù)架構(gòu)中的服務(wù)治理非常有用。

在使用 Nacos 動態(tài)路由時,如果服務(wù)下線了,Spring Cloud Gateway 會如何響應(yīng)?

當(dāng)使用 Nacos 動態(tài)路由時,如果服務(wù)下線,Spring Cloud Gateway 會通過 Nacos 的服務(wù)發(fā)現(xiàn)機(jī)制感知到這一變化,并根據(jù)配置的動態(tài)路由規(guī)則進(jìn)行調(diào)整。如何配置 Spring Cloud Gateway 以響應(yīng)服務(wù)下線的情況呢?來,上代碼:

首先,確保咱們的項目中已經(jīng)添加了 Spring Cloud Gateway 和 Spring Cloud Alibaba Nacos Discovery 的依賴。

1. application.yml 配置

application.yml 中配置 Nacos 服務(wù)發(fā)現(xiàn)和動態(tài)路由:

spring:
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848 # Nacos 服務(wù)地址
    gateway:
      routes:
        - id: my-service-route
          uri: lb://MY-SERVICE
          predicates:
            - Path=/my-service/**
          filters:
            - StripPrefix=1
      discovery:
        locator:
          enabled: true
          lower-case-service-id: true

2. Nacos 配置中心的動態(tài)路由配置

在 Nacos 配置中心創(chuàng)建一個名為 gateway-routes.json 的配置文件,內(nèi)容如下:

{
  "spring": {
    "cloud": {
      "gateway": {
        "routes": [
          {
            "id": "my-service-route",
            "uri": "lb://MY-SERVICE",
            "predicates": [
              {
                "name": "Path",
                "args": {
                  "_genkey_0": "/my-service/**"
                }
              }
            ],
            "filters": [
              {
                "name": "StripPrefix",
                "args": {
                  "_genkey_1": "1"
                }
              }
            ]
          }
        ]
      }
    }
  }
}

3. 動態(tài)路由配置監(jiān)聽

創(chuàng)建一個配置類來監(jiān)聽 Nacos 配置變化,并刷新路由規(guī)則:

import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.model.Properties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionRepository;
import org.springframework.cloud.gateway.route.RoutesRefreshedEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import java.util.Properties as JavaProperties;

@Component
public class NacosDynamicRoute implements ApplicationRunner {

    @Autowired
    private RouteDefinitionRepository routeDefinitionRepository;

    @Autowired
    private ApplicationEventPublisher publisher;

    private ConfigService configService;

    public NacosDynamicRoute(NacosConfigProperties properties) throws NacosException {
        JavaProperties javaProperties = new JavaProperties();
        javaProperties.setProperty("serverAddr", properties.getServerAddr());
        javaProperties.setProperty("namespace", properties.getNamespace());
        configService = NacosFactory.createConfigService(javaProperties);
    }

    @Override
    public void run(ApplicationArguments args) {
        try {
            String routeJson = configService.getConfig("gateway-routes.json", "DEFAULT_GROUP", 5000);
            refreshRoutes(routeJson);
            configService.addListener("gateway-routes.json", "DEFAULT_GROUP", s -> refreshRoutes(s));
        } catch (NacosException e) {
            e.printStackTrace();
        }
    }

    private void refreshRoutes(String routeJson) {
        SpringCloudRouteDefinition routeDefinition = JsonUtils.deserialize(routeJson, SpringCloudRouteDefinition.class);
        routeDefinitionRepository.delete("*").subscribe();
        routeDefinitionRepository.save(routeDefinition.getRouteDefinitions()).subscribe();
        publisher.publishEvent(new RoutesRefreshedEvent(this));
    }

    // 內(nèi)部類,用于反序列化 Nacos 配置
    static class SpringCloudRouteDefinition {
        private RouteDefinition[] routeDefinitions;

        // getter 和 setter 省略
    }
}

NacosDynamicRoute 類會在應(yīng)用啟動時從 Nacos 配置中心加載路由配置,并注冊一個監(jiān)聽器來監(jiān)聽配置變化。當(dāng)配置發(fā)生變化時,它會重新加載路由配置并刷新路由規(guī)則。

以上就是使用Nacos實現(xiàn)動態(tài)路由的步驟和代碼示例的詳細(xì)內(nèi)容,更多關(guān)于Nacos動態(tài)路由的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Ajax實現(xiàn)搜索引擎自動補全功能

    Ajax實現(xiàn)搜索引擎自動補全功能

    本文主要介紹了Ajax實現(xiàn)搜索引擎自動補全功能的實例解析。具有很好的參考價值。下面跟著小編一起來看下吧
    2017-04-04
  • 基于HttpClient上傳文件中文名亂碼的解決

    基于HttpClient上傳文件中文名亂碼的解決

    這篇文章主要介紹了HttpClient上傳文件中文名亂碼的解決方案,具有很好的參考價值,希望對大家有所幫助。
    2021-07-07
  • 關(guān)于MyBatis的foreach標(biāo)簽常用方法

    關(guān)于MyBatis的foreach標(biāo)簽常用方法

    這篇文章主要介紹了關(guān)于MyBatis的foreach標(biāo)簽常用方法,foreach 標(biāo)簽可以用來遍歷數(shù)組、列表和 Map 等集合參數(shù),實現(xiàn)批量操作或一些簡單 SQL 操作,需要的朋友可以參考下
    2023-05-05
  • Java?SE使用for?each循環(huán)遍歷數(shù)組的方法代碼

    Java?SE使用for?each循環(huán)遍歷數(shù)組的方法代碼

    在Java?SE開發(fā)中,數(shù)組是最常見的數(shù)據(jù)結(jié)構(gòu)之一,Java提供了多種遍歷數(shù)組的方式,其中for循環(huán)是最常用的方式之一,本文將介紹如何使用for?each循環(huán)遍歷數(shù)組,接下來,我們將通過一個簡單的代碼示例來展示如何使用for?each循環(huán)遍歷數(shù)組,需要的朋友可以參考下
    2023-11-11
  • Java字符串String相關(guān)類常用方法詳解

    Java字符串String相關(guān)類常用方法詳解

    這篇文章主要介紹了Java中的字符串?dāng)?shù)據(jù)類型,包括字符串的創(chuàng)建、拼接、比較和常用方法,還介紹了StringBuilder和StringJoiner類的定義和使用,以及它們在內(nèi)存中的管理方式,需要的朋友可以參考下
    2025-02-02
  • 淺談Java 將圖片打包到j(luò)ar中的路徑問題

    淺談Java 將圖片打包到j(luò)ar中的路徑問題

    下面小編就為大家分享一篇淺談Java 將圖片打包到j(luò)ar中的路徑問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-02-02
  • Springboot2 配置AOP日志的方法步驟

    Springboot2 配置AOP日志的方法步驟

    這篇文章主要介紹了Springboot2 配置AOP日志的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-06-06
  • mybatis條件語句中帶數(shù)組參數(shù)的處理

    mybatis條件語句中帶數(shù)組參數(shù)的處理

    這篇文章主要介紹了mybatis條件語句中帶數(shù)組參數(shù)的處理方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • spring中websocket定時任務(wù)實現(xiàn)實時推送

    spring中websocket定時任務(wù)實現(xiàn)實時推送

    本文主要介紹了spring中websocket定時任務(wù)實現(xiàn)實時推送,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-01-01
  • springboot?log4j2.xml如何讀取application.yml中屬性值

    springboot?log4j2.xml如何讀取application.yml中屬性值

    這篇文章主要介紹了springboot?log4j2.xml如何讀取application.yml中屬性值問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-12-12

最新評論

溧阳市| 双城市| 万山特区| 清涧县| 云安县| 绥德县| 西乌珠穆沁旗| 怀来县| 响水县| 阳山县| 新丰县| 凭祥市| 绩溪县| 渑池县| 霞浦县| 长岭县| 磐石市| 关岭| 青川县| 浪卡子县| 江城| 洛阳市| 光泽县| 伊春市| 拉孜县| 黄平县| 慈溪市| 宾阳县| 吴忠市| 鹿邑县| 隆昌县| 蒙自县| 临邑县| 马公市| 偃师市| 宜宾县| 大理市| 青铜峡市| 新巴尔虎右旗| 循化| 梁河县|