上文介绍到Sentinel的规则如果需要持久化,就需要采用推或者拉模式
本文采用Nacos也就是推模式持久化规则,这种方式的交互就切断了Sentinel客户端和 Sentinel Dashboard的联系。它的交互方式是这样:当Sentinel Dashboard有规则变更后,会推送到Nacos,再又Nacos推送给客户端,如下图所示:
这种方式需要修改两处地方:
1、修改 Sentinel Dashboard源码(其实Dashboard已经接入了nacos,我们只需要替换一下默认的实现)
2、Sentinel客户端接入Nacos
修改 Sentinel Dashboard源码
1、下载Sentinel Dashboard项目
https://github.com/alibaba/Sentinel/tree/master/sentinel-dashboard
2、将test目录下关于Nacos拷贝到com.alibaba.csp.sentinel.dashboard.rule
其中FlowRuleNacosProvider会从Nacos中拉取规则,FlowRuleNacosPublisher会向Nacos推送规则,这是Dashboard为我们提供的实现
3、然后替换FlowControllerV2类中DynamicRuleProvider为Nacos的实现
4、然后前端页面也要改成调用v2的接口,默认是调用/v1/flow
sidebar.html(resources/app/scripts/directives/sidebar)页面
控规则路由从 dashboard.flowV1
改成 dashboard.flow
app.js(resources/dist/js/app.js)将app/scripts/controllers/flow_v1.js
替换为app/scripts/controllers/flow_v2.js
Sentinel Dashboard修改完成!!
Sentinel客户端接入Nacos
2、Sentinel 针对 Nacos 作了适配,底层可以采用 Nacos 作为规则配置数据源。使用时只需添加以下依赖:
- <dependency>
- <groupId>com.alibaba.csp</groupId>
- <artifactId>sentinel-datasource-nacos</artifactId>
- <version>1.8.0</version>
- </dependency>
完整依赖:
- <!-- 依赖web -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <!-- sentinel springboot-starter -->
- <dependency>
- <groupId>com.alibaba.cloud</groupId>
- <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
- <version>2021.1</version>
- </dependency>
- <!-- sentinel 核心依赖-->
- <dependency>
- <groupId>com.alibaba.csp</groupId>
- <artifactId>sentinel-core</artifactId>
- <version>1.8.0</version>
- </dependency>
- <!--sentinel持久化 -->
- <dependency>
- <groupId>com.alibaba.csp</groupId>
- <artifactId>sentinel-datasource-nacos</artifactId>
- <version>1.8.0</version>
- </dependency>
Yml配置
- server:
- port: 8081
- spring:
- application:
- name: sentinel
- cloud:
- nacos:
- discovery:
- server-addr: 127.0.0.1:8848
- sentinel:
- transport:
- dashboard: 127.0.0.1:8080 #指定sentinel dashboard web 地址
- datasource:
- ds1: #名称自定义,唯一
- nacos:
- server-addr: 127.0.0.1:8848
- dataId: ${spring.application.name}-flow-rules
- groupId: SENTINEL_GROUP
- data-type: json
- rule-type: flow
其中dataId和groupId要和Sentinel Dashboard中FlowRuleNacosPublisher所push的一致,默认值如下,所以我们也设置成默认值即可
然后依次启动Sentinel Dashboard和Sentinel客户端即可,从Dashboard中修改的规则会立马推送到Nacos,从Nacos添加的规则Dashboard也能感知到,且就算客户端或者Dashboard重启,数据也能从Nacos中读取出来,做到了持久化