使用 Nacos 实现动态路由

2024-09-04 20:36

本文主要是介绍使用 Nacos 实现动态路由,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Hello,大家好,我是 V 哥。最近写到 使用 Nacos 实现动态路由的问题,整理了一下思路和案例,分享给大家。

使用 Nacos 实现 Spring Cloud Gateway 的动态路由,主要涉及到以下几个步骤:

  1. 添加依赖:在 Spring Cloud Gateway 应用的 pom.xml 文件中添加 Nacos 相关依赖。

  2. 配置 Nacos:在 application.ymlapplication.properties 文件中配置 Nacos 服务地址。

  3. 启用动态路由:在配置文件中启用 Nacos 动态路由功能。

  4. 创建动态路由配置:在 Nacos 配置中心创建动态路由的配置信息。

  5. 监听配置变化:在 Spring Cloud Gateway 应用中监听 Nacos 配置变化,动态更新路由规则。

下面是具体的实现步骤和代码案例,来看一下:

1. 添加依赖

pom.xml 文件中添加 Spring Cloud Gateway 和 Nacos 相关依赖:

<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 服务地址:

spring:cloud:nacos:discovery:server-addr: 127.0.0.1:8848 # Nacos 服务地址config:server-addr: 127.0.0.1:8848 # Nacos 配置中心地址file-extension: yml # 配置文件格式group: DEFAULT_GROUP # 配置分组namespace: # 配置命名空间

3. 启用动态路由

application.yml 文件中启用 Nacos 动态路由功能:

spring:cloud:gateway:discovery:locator:enabled: true # 开启从注册中心动态创建路由的功能lower-case-service-id: true # 使用小写服务名,默认是大写

4. 创建动态路由配置

在 Nacos 配置中心创建一个配置文件,例如 gateway-routes.yml,内容如下:

spring:cloud:gateway:routes:- id: my-service-routeuri: lb://MY-SERVICEpredicates:- Path=/my-service/**filters:- StripPrefix=1

5. 监听配置变化

在 Spring Cloud Gateway 应用中,创建一个配置类来监听 Nacos 配置变化,并刷新路由规则:

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;}@EventListenerpublic void onEnvironmentChange(EnvironmentChangeEvent event) {if (event.getKeys().contains("spring.cloud.gateway.routes")) {routeDefinitionLocator.getRouteDefinitions().subscribe(routeDefinitions -> {routeDefinitionWriter.delete("*").subscribe();routeDefinitionWriter.save(routeDefinitions).subscribe();});}}
}

这个类会监听环境变化事件,当检测到 spring.cloud.gateway.routes 配置项发生变化时,会重新加载和刷新路由规则。

我们通过使用 Nacos 实现 Spring Cloud Gateway 的动态路由。通过在 Nacos 配置中心维护路由配置,可以实现不重启网关服务的情况下动态更新路由规则,这对于微服务架构中的服务治理非常有用。

在使用 Nacos 动态路由时,如果服务下线了,Spring Cloud Gateway 会如何响应?

当使用 Nacos 动态路由时,如果服务下线,Spring Cloud Gateway 会通过 Nacos 的服务发现机制感知到这一变化,并根据配置的动态路由规则进行调整。如何配置 Spring Cloud Gateway 以响应服务下线的情况呢?来,上代码:

首先,确保咱们的项目中已经添加了 Spring Cloud Gateway 和 Spring Cloud Alibaba Nacos Discovery 的依赖。

1. application.yml 配置

application.yml 中配置 Nacos 服务发现和动态路由:

spring:cloud:nacos:discovery:server-addr: 127.0.0.1:8848 # Nacos 服务地址gateway:routes:- id: my-service-routeuri: lb://MY-SERVICEpredicates:- Path=/my-service/**filters:- StripPrefix=1discovery:locator:enabled: truelower-case-service-id: true

2. Nacos 配置中心的动态路由配置

在 Nacos 配置中心创建一个名为 gateway-routes.json 的配置文件,内容如下:

{"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. 动态路由配置监听

创建一个配置类来监听 Nacos 配置变化,并刷新路由规则:

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 {@Autowiredprivate RouteDefinitionRepository routeDefinitionRepository;@Autowiredprivate 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);}@Overridepublic 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));}// 内部类,用于反序列化 Nacos 配置static class SpringCloudRouteDefinition {private RouteDefinition[] routeDefinitions;// getter 和 setter 省略}
}

NacosDynamicRoute 类会在应用启动时从 Nacos 配置中心加载路由配置,并注册一个监听器来监听配置变化。当配置发生变化时,它会重新加载路由配置并刷新路由规则。点赞+关注,学习 Java 不迷路。

这篇关于使用 Nacos 实现动态路由的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1136966

相关文章

Android Paging 分页加载库使用实践

《AndroidPaging分页加载库使用实践》AndroidPaging库是Jetpack组件的一部分,它提供了一套完整的解决方案来处理大型数据集的分页加载,本文将深入探讨Paging库... 目录前言一、Paging 库概述二、Paging 3 核心组件1. PagingSource2. Pager3.

python设置环境变量路径实现过程

《python设置环境变量路径实现过程》本文介绍设置Python路径的多种方法:临时设置(Windows用`set`,Linux/macOS用`export`)、永久设置(系统属性或shell配置文件... 目录设置python路径的方法临时设置环境变量(适用于当前会话)永久设置环境变量(Windows系统

python使用try函数详解

《python使用try函数详解》Pythontry语句用于异常处理,支持捕获特定/多种异常、else/final子句确保资源释放,结合with语句自动清理,可自定义异常及嵌套结构,灵活应对错误场景... 目录try 函数的基本语法捕获特定异常捕获多个异常使用 else 子句使用 finally 子句捕获所

C++11右值引用与Lambda表达式的使用

《C++11右值引用与Lambda表达式的使用》C++11引入右值引用,实现移动语义提升性能,支持资源转移与完美转发;同时引入Lambda表达式,简化匿名函数定义,通过捕获列表和参数列表灵活处理变量... 目录C++11新特性右值引用和移动语义左值 / 右值常见的左值和右值移动语义移动构造函数移动复制运算符

Python对接支付宝支付之使用AliPay实现的详细操作指南

《Python对接支付宝支付之使用AliPay实现的详细操作指南》支付宝没有提供PythonSDK,但是强大的github就有提供python-alipay-sdk,封装里很多复杂操作,使用这个我们就... 目录一、引言二、准备工作2.1 支付宝开放平台入驻与应用创建2.2 密钥生成与配置2.3 安装ali

Spring Security 单点登录与自动登录机制的实现原理

《SpringSecurity单点登录与自动登录机制的实现原理》本文探讨SpringSecurity实现单点登录(SSO)与自动登录机制,涵盖JWT跨系统认证、RememberMe持久化Token... 目录一、核心概念解析1.1 单点登录(SSO)1.2 自动登录(Remember Me)二、代码分析三、

C#中lock关键字的使用小结

《C#中lock关键字的使用小结》在C#中,lock关键字用于确保当一个线程位于给定实例的代码块中时,其他线程无法访问同一实例的该代码块,下面就来介绍一下lock关键字的使用... 目录使用方式工作原理注意事项示例代码为什么不能lock值类型在C#中,lock关键字用于确保当一个线程位于给定实例的代码块中时

MySQL 强制使用特定索引的操作

《MySQL强制使用特定索引的操作》MySQL可通过FORCEINDEX、USEINDEX等语法强制查询使用特定索引,但优化器可能不采纳,需结合EXPLAIN分析执行计划,避免性能下降,注意版本差异... 目录1. 使用FORCE INDEX语法2. 使用USE INDEX语法3. 使用IGNORE IND

C# $字符串插值的使用

《C#$字符串插值的使用》本文介绍了C#中的字符串插值功能,详细介绍了使用$符号的实现方式,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧... 目录$ 字符使用方式创建内插字符串包含不同的数据类型控制内插表达式的格式控制内插表达式的对齐方式内插表达式中使用转义序列内插表达式中使用

flask库中sessions.py的使用小结

《flask库中sessions.py的使用小结》在Flask中Session是一种用于在不同请求之间存储用户数据的机制,Session默认是基于客户端Cookie的,但数据会经过加密签名,防止篡改,... 目录1. Flask Session 的基本使用(1) 启用 Session(2) 存储和读取 Se