使用 Nacos 实现 Spring Cloud Gateway 的动态路由

您所在的位置:网站首页 nacos和gateway 使用 Nacos 实现 Spring Cloud Gateway 的动态路由

使用 Nacos 实现 Spring Cloud Gateway 的动态路由

2024-07-14 23:13:09| 来源: 网络整理| 查看: 265

使用 Nacos 实现 Spring Cloud Gateway 的动态路由

摘要: 本文主要介绍通过 Nacos 下发路由配置实现 Spring Cloud Gateway 的动态路由.

1. 前言

网关中有两个重要的概念, 那就是路由配置和路由规则, 路由配置是指配置某请求路径路由到指定的目的地址. 而路由规则是指匹配到路由配置之后, 再根据路由规则进行转发处理. Spring Cloud Gateway 作为所有请求流量的入口, 在实际生产环境中为了保证高可靠和高可用, 尽量避免重启, 需要实现 Spring Cloud Gateway 动态路由配置. 前面章节介绍了 Spring Cloud Gateway 提供的两种方法去配置路由规则, 但都是在 Spring Cloud Gateway 启动时候, 就将路由配置和规则加载到内存里, 无法做到不重启网关就可以动态的对应路由的配置和规则进行增加, 修改和删除. 本文是基于 Spring Cloud Gateway 的动态路由实现基础之上编写, 通过 Nacos 配置服务下发路由配置实现动态路由.

2. Spring Cloud Gateway 简单的动态路由实现

Spring Cloud Gateway 的官方文档并没有讲如何动态配置, 查看 Spring Cloud Gateway 的源码, 发现 在 org.springframework.cloud.gateway.actuate.GatewayControllerEndpoint 类中提供了动态配置的 REST 接口, 但是 需要开启 Gateway 的端点, 而且提供的功能不是很强大. 通过参考和 GatewayControllerEndpoint 相关的代码, 可以自己编码实际动态路由配置. 下面通过案例的方式去讲解怎么通 Nacos 实现 Spring Cloud Gateway 的动态路由. 案例工程如 spring-cloud-gateway-nacos 所示.

代码地址: https://github.com/SpringCloud/spring-cloud-gateway-nacos

3. 简单动态路由的实现

3.1 新建 Maven 工程 sc-gateway-server

配置主要的核心依赖如代码清单所示: 代码清单: spring-cloud-gateway-nacos/sc-gateway-server/pom.xml

org.springframework.cloud spring-cloud-starter-gateway com.alibaba.nacos nacos-client 0.4.0 org.springframework.boot spring-boot-starter-webflux org.springframework.boot spring-boot-starter-actuator com.alibaba fastjson 1.2.47

3.2 根据 Spring Cloud Gateway 的路由模型定义数据传输模型

分别创建 GatewayRouteDefinition.java, GatewayPredicateDefinition.java, GatewayFilterDefinition.java 这三个类. (1) 创建路由定义模型

public class GatewayRouteDefinition { // 路由的 Id private String id; // 路由断言集合配置 private List predicates = new ArrayList(); // 路由过滤器集合配置 private List filters = new ArrayList(); // 路由规则转发的目标 uri private String uri; // 路由执行的顺序 private int order = 0; // 此处省略 get 和 set 方法}

(2) 创建过滤器定义模型

public class GatewayFilterDefinition { //Filter Name private String name; // 对应的路由规则 private Map args = new LinkedHashMap(); // 此处省略 Get 和 Set 方法}

(3) 创建路由断言定义模型

public class GatewayPredicateDefinition { // 断言对应的 Name private String name; // 配置的断言规则 private Map args = new LinkedHashMap(); // 此处省略 Get 和 Set 方法}

3.3 编写动态路由实现类

编写 DynamicRouteServiceImpl 并实现 ApplicationEventPublisherAware 接口, 代码如下所示

@Servicepublic class DynamicRouteServiceImpl implements ApplicationEventPublisherAware { @Autowired private RouteDefinitionWriter routeDefinitionWriter; private ApplicationEventPublisher publisher; // 增加路由 public String add(RouteDefinition definition) { routeDefinitionWriter.save(Mono.just(definition)).subscribe(); this.publisher.publishEvent(new RefreshRoutesEvent(this)); return "success"; } // 更新路由 public String update(RouteDefinition definition) { try { this.routeDefinitionWriter.delete(Mono.just(definition.getId())); } catch (Exception e) { return "update fail,not find route routeId:"+definition.getId(); } try { routeDefinitionWriter.save(Mono.just(definition)).subscribe(); this.publisher.publishEvent(new RefreshRoutesEvent(this)); return "success"; } catch (Exception e) { return "update route fail"; } } // 删除路由 public Mono delete(String id) { return this.routeDefinitionWriter.delete(Mono.just(id)) .then(Mono.defer(() -> Mono.just(ResponseEntity.ok().build()))) .onErrorResume(t -> t instanceof NotFoundException, t -> Mono.just(ResponseEntity.notFound().build())); } @Override public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.publisher = applicationEventPublisher; }}

3.4 编写 Nacos 监听接收下发的路由配置

3.4.1 使用 Nacos 监听下发的配置

监听 Nacos Config Server 下发配置的代码如下所示:

@Componentpublic class DynamicRouteServiceImplByNacos { @Autowired private DynamicRouteServiceImpl dynamicRouteService; public DynamicRouteServiceImplByNacos() { dynamicRouteByNacosListener("sc-gateway","xujin_test"); } /** * 监听 Nacos Server 下发的动态路由配置 * @param dataId * @param group */ public void dynamicRouteByNacosListener (String dataId, String group){ try { ConfigService configService=NacosFactory.createConfigService("127.0.0.1:8848"); String content = configService.getConfig(dataId, group, 5000); System.out.println(content); configService.addListener(dataId, group, new Listener() { @Override public void receiveConfigInfo(String configInfo) { RouteDefinition definition= JSON.parseObject(configInfo,RouteDefinition.class); dynamicRouteService.update(definition); } @Override public Executor getExecutor() { return null; } }); } catch (NacosException e) { //todo 提醒: 异常自行处理此处省略 } }}

3.4.2 两种方式创建 ConfigService

使用两种方式创建 com.alibaba.nacos.API.config.ConfigService

1. 构建 Properties 创建

使用 createConfigService(Properties properties), 代码如下所示:

Properties properties = new Properties(); properties.put("nacos.server-addr", ""); properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848"); ConfigService configService=NacosFactory.createConfigService(properties);

注意: PropertyKeyConst 是 com.alibaba.nacos.API.PropertyKeyConst

2. 只传递 Nacos Config Server 的地址

ConfigService configService=NacosFactory.createConfigService("127.0.0.1:8848");

4. 使用 Nacos 下发配置

4.1 Nacos 概述

Naocs 由阿里开源, Nacos 致力于帮助您发现, 配置和管理微服务. Nacos 提供了一组简单易用的特性集, 帮助您快速实现动态服务发现, 服务配置, 服务元数据及流量管理. Nacos 帮助您更敏捷和容易地构建, 交付和管理微服务平台. Nacos 是构建以 "服务" 为中心的现代应用架构 (例如微服务范式, 云原生范式) 的服务基础设施. GitHub 地址: https://github.com/alibaba/nacos

更多 Nacos 的介绍, 请访问官方网站: https://nacos.io/

4.2 在 IDE 中启动 Nacos

访问 https://github.com/alibaba/nacos , 使用 Git 克隆 Nacos 代码, 直接导入到 IDEA 中, 如下所示设置启动参数, 直接启动.

从 IDE 中启动 Nacos 是我比较推荐的方式, 因为可以随时 Debug Nacos 任何代码, 其它启动方式请参考官网.

5. 测试

5.1 Nacos 中下发 Spring Cloud Gateway 的路由配置

1. 打开浏览器访问 URL:http://localhost:8848/nacos/index.html ,Nacos 的管控平台如下所示:

2. 在 Nacos 的配置列表点击 + 按钮, 下发 Spring Cloud Gateway 的路由配置, 如下所示:

用于测试的示例数据, 如下所示:

{ "filters": [], "id": "jd_route", "order": 0, "predicates": [{ "args": { "pattern": "/jd" }, "name": "Path" }], "uri": "http://www.jd.com"}

5.2 启动 sc-gateway-server

1.Debug 启动 sc-gateway-server, 调试截图如下所示:

2. 通过 Spring Cloud gateway 的端点, 查看路由信息

3. 通过访问 http://localhost:8080/jd , 可以转发到京东商城主页

5.3 更新路由配置

1. 通过 Nacos 下发配置, 修改 Spring Cloud Gateway 的动态路由规则

2. 查看访问 Spring Cloud gateway 的端点配置, 可以看到动态路由修改如下:

3. 通过访问 http://localhost:8080/jd , 可以转发到百度相关页面

来源: https://juejin.im/entry/5bf789ef6fb9a049f745d8c9

与本文相关文章 Spring Cloud Gateway 的动态路由怎样做? 集成 Nacos 实现很简单 Spring-Cloud-Gateway 源码解析 —— 路由(2.4)之 Kotlin 自定义 RouteLocator Spring Cloud 体系实现标签路由 使用动态路由协议 Spring-Cloud-Gateway 源码解析 —— 路由(1.1)之 RouteDefinitionLocator 一览 基于 Spring Cloud Gateway 的路由实践 SpringCloud-Gateway 网关路由, 断言, 过滤 动态 RIP 配置路由表


【本文地址】

公司简介

联系我们

今日新闻


点击排行

实验室常用的仪器、试剂和
说到实验室常用到的东西,主要就分为仪器、试剂和耗
不用再找了,全球10大实验
01、赛默飞世尔科技(热电)Thermo Fisher Scientif
三代水柜的量产巅峰T-72坦
作者:寞寒最近,西边闹腾挺大,本来小寞以为忙完这
通风柜跟实验室通风系统有
说到通风柜跟实验室通风,不少人都纠结二者到底是不
集消毒杀菌、烘干收纳为一
厨房是家里细菌较多的地方,潮湿的环境、没有完全密
实验室设备之全钢实验台如
全钢实验台是实验室家具中较为重要的家具之一,很多

推荐新闻


图片新闻

实验室药品柜的特性有哪些
实验室药品柜是实验室家具的重要组成部分之一,主要
小学科学实验中有哪些教学
计算机 计算器 一般 打孔器 打气筒 仪器车 显微镜
实验室各种仪器原理动图讲
1.紫外分光光谱UV分析原理:吸收紫外光能量,引起分
高中化学常见仪器及实验装
1、可加热仪器:2、计量仪器:(1)仪器A的名称:量
微生物操作主要设备和器具
今天盘点一下微生物操作主要设备和器具,别嫌我啰嗦
浅谈通风柜使用基本常识
 众所周知,通风柜功能中最主要的就是排气功能。在

专题文章

    CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭