Sentinel 如何持久化数据到 Nacos?

默认情况下 Sentinel 只能接收到 Nacos 推送的消息,但不能将自己控制台修改的信息同步给 Nacos,如下图所示:

但是在生成环境下,我们为了更方便的操作,是需要将 Sentinel 控制台修改的规则也同步到 Nacos 的,所以在这种情况下我们就需要修改 Sentinel 的源码,让其可以实现和 Nacos 的双向通讯,如下图所示:

改造之后的交互流程如下图所示:

Sentinel 同步规则至数据源,例如将 Sentinel 的规则,同步规则至 Nacos 数据源的改造步骤很多,但整体实现难度不大,下面我们一起来看吧。
1.下载 Sentinel 源码
下载地址:https://github.com/alibaba/Sentinel
PS:本文 Sentinel 使用的版本是 1.8.6。
下载源码之后,使用 idea 打开里面的 sentinel-dashboard 项目,如下图所示:

2.修改 pom.xml
将 sentinel-datasource-nacos 底下的 scope 注释掉,如下图所示:

PS:因为官方提供的 Nacos 持久化实例,是在 test 目录下进行单元测试的,而我们是用于生产环境,所以需要将 scope 中的 test 去掉。
3.移动单元测试代码
将 test/com.alibaba.csp.sentinel.dashboard.rule.nacos 下所有文件复制到 src/main/java/com.alibaba.csp.sentinel.dashboard.rule 目录下,如下图所示:

4.新建 NacosPropertiesConfiguration 文件
在 com.alibaba.csp.sentinel.dashboard.rule 下创建 Nacos 配置文件的读取类,实现代码如下:
5.修改 NacosConfig 文件
只修改 NacosConfig 中的 nacosConfigService 方法,修改后的代码如下:
6.修改 FlowControllerV2 文件
修改 com.alibaba.csp.sentinel.dashboard.controller.v2 目录下的 FlowControllerV2 文件:

修改后代码:
PS:此操作的目的是开启 Controller 层操作 Nacos 的开关。
如下图所示:

7.修改配置信息
在 application.properties 中设置 Nacos 连接信息,配置如下:
8.修改 sidebar.html
修改 webapp/resources/app/scripts/directives/sidebar/sidebar.html 文件:

搜索“dashboard.flowV1”改为“dashboard.flow”,如下图所示:

9.修改 identity.js
identity.js 文件有两处修改,它位于 webapp/resources/app/scripts/controllers/identity.js 目录。
9.1 第一处修改
将“FlowServiceV1”修改为“FlowServiceV2”,如下图所示:

9.2 第二处修改
搜索“/dashboard/flow/”修改为“/dashboard/v2/flow/”,如下图所示:

PS:修改 identity.js 文件主要是用于在 Sentinel 点击资源的“流控”按钮添加规则后将信息同步给 Nacos。
小结
Sentinel Dashboard 默认情况下,只能将配置规则保存到内存中,这样就会程序重启后配置规则丢失的情况,因此我们需要给 Sentinel 设置一个数据源,并且要和数据源之间实现双向通讯,所以我们需要修改 Sentinel 的源码。源码的改造步骤虽然很多,但只要逐一核对和修改就可以实现 Sentinel 生成环境的配置了。
本文已收录到我的面试小站 www.javacn.site,其中包含的内容有:Redis、JVM、并发、并发、MySQL、Spring、Spring MVC、Spring Boot、Spring Cloud、MyBatis、设计模式、消息队列等模块。
评论