Sentinel 源码改造,实现 Nacos 双向通信!

Sentinel Dashboard(控制台)默认情况下,只能将配置规则保存到内存中,这样就会导致 Sentinel Dashboard 重启后配置规则丢失的情况,因此我们需要将规则保存到某种数据源中,Sentinel 支持的数据源有以下这些:

然而,默认情况下,Sentinel 和数据源之间的关系是单向数据通讯的,也就是只能先在数据源中配置规则,然后数据源会被规则推送至 Sentinel Dashboard 和 Sentinel 客户端,但是在 Sentinel Dashboard 中修改规则或新增规则是不能反向同步到数据源中的,这就是单向通讯。
所以,今天我们就该修改一下 Sentinel 的源码,让其可以同步规则至数据源,改造之后的交互流程如下图所示:

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、设计模式、消息队列等模块。
评论