Sentinel 规则持久化到 Nacos 实战
前言:
前面系列文章我们对 Sentinel 的作用及工作流程源码进行了分析,我们知道 Sentinel 的众多功能都是通过规则配置完成的,但是我们前面在演示的时候,发现 Sentinel 一重启,配置的规则就没有了,这是因为规则存储在内存中,本篇我们来实现 Sentinel 规则持久化到 Nacos 中。
Sentinel 系列文章传送门:
Sentinel 初步认识及使用
Sentinel 核心概念和工作流程详解
Spring Cloud 整合 Nacos、Sentinel、OpenFigen 实战【微服务熔断降级实战】
Sentinel 源码分析入门【Entry、Chain、Context】
Sentine 源码分析之–NodeSelectorSlot、ClusterBuilderSlot、StatisticSlot
Sentine 源码分析之–AuthoritySlot、SystemSlot、GatewayFlowSlot
Sentine 源码分析之–ParamFlowSlot
Sentine 源码分析之–FlowSlot
Sentinel 滑动时间窗口源码分析
Sentinel 的三种规则管理模式
- 原始模式:规则直接保存在内存中,这种模式比较简单,不依赖外部组件,但是有一个致命的问题,重启规则就不存在了,生产环境不可能使用这种模式。
- Pull 模式:控制台将配置的规则推送到 Sentinel客户端,而客户端会将配置规则保存在本地文件或数据库中,定时去本地文件或数据库中查询,更新本地规则,这种模式也比较简单,不依赖外部组件,但是实时性不保证,拉取过于频繁也可能会有性能问题,因此也不建议生产环境使用。
- Push 模式:控制台将配置规则推送到远程配置中心,例如 Nacos、ZooKeeper、Apollo 等,Sentinel 客户端监听 Nacos、ZooKeeper、Apollo,获取配置变更的推送消息,完成本地配置更新,推荐生产环境使用。
本篇分享的是使用 Nacos 来实现 Sentinel 规则持久化。
Sentinel 源码改造
后端源码修改
Sentinel Dashboard 默认不支持 Nacos 的持久化,需要修改 Sentinel Dashboard 源码。
1.修改 pom.xml 文件,在 sentinel-dashboard 源码 pom 文件中,Nacos 的依赖默认的 scope 是 test,表示只能在测试时使用,这里要去掉,如下:
<!-- for Nacos rule publisher sample -->
<dependency><groupId>com.alibaba.csp</groupId><artifactId>sentinel-datasource-nacos</artifactId><!-- <scope>test</scope>-->
</dependency>
2.添加对 Nacos 的支持,Sentinel 已经提供了 Nacos 的支持,只不过代码在 src/test/rule 下面,我们需要把他复制到 src/test/rule 下面,如下:
3.修改 Nacos 地址,也就是对 NacosConfig 源码进行修改,修改后的源码如下:
package com.alibaba.csp.sentinel.dashboard.rule.nacos;import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.FlowRuleEntity;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigFactory;
import com.alibaba.nacos.api.config.ConfigService;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import java.util.List;
import java.util.Properties;/*** @author Eric Zhao* @since 1.4.0*/
@Configuration
@ConfigurationProperties(prefix = "nacos")//需要增加的
public class NacosConfig {//需要自己增加的 Nacos 地址private String addr;//需要自己增加的 Nacos 地址private String namespace;//需要自己增加的public String getAddr() {return addr;}//需要自己增加的public void setNamespace(String namespace) {this.namespace = namespace;}//需要自己增加的public String getNamespace() {return namespace;}//需要自己增加的public void setAddr(String addr) {this.addr = addr;}@Beanpublic Converter<List<FlowRuleEntity>, String> flowRuleEntityEncoder() {return JSON::toJSONString;}@Beanpublic Converter<String, List<FlowRuleEntity>> flowRuleEntityDecoder() {return s -> JSON.parseArray(s, FlowRuleEntity.class);}/*@Beanpublic ConfigService nacosConfigService() throws Exception {return ConfigFactory.createConfigService("localhost");}*///修改后的注入 ConfigService 方法@Beanpublic ConfigService nacosConfigService() throws Exception {Properties properties = new Properties();properties.put(PropertyKeyConst.SERVER_ADDR, addr);properties.put(PropertyKeyConst.NAMESPACE, namespace);return ConfigFactory.createConfigService(properties);}
}
修改 Nacos 源码后,还需要修改 sentinel-dashboard 的 application.properties 中的 nacos 地址,如下:
nacos.addr=localhost:8848
nacos.namespace=sentinel
- 配置nacos数据源,需要修改 com.alibaba.csp.sentinel.dashboard.controller.v2 包下的 FlowControllerV2 类,修改源码如下:
public class FlowControllerV2 {private final Logger logger = LoggerFactory.getLogger(FlowControllerV2.class);@Autowiredprivate InMemoryRuleRepositoryAdapter<FlowRuleEntity> repository;@Autowired//注释掉默认的 flowRuleDefaultProvider//@Qualifier("flowRuleDefaultProvider")@Qualifier("flowRuleNacosProvider")private DynamicRuleProvider<List<FlowRuleEntity>> ruleProvider;@Autowired注释掉默认的 flowRuleDefaultPublisher//@Qualifier("flowRuleDefaultPublisher")@Qualifier("flowRuleNacosPublisher")private DynamicRulePublisher<List<FlowRuleEntity>> rulePublisher;//省略部分代码。。。。。。}
前端源码修改
1.修改流控规则,找到 resources/app/scripts/directives/sidebar/sidebar.html 文件中的流控规则,修改后源码如下:
2.修改簇点链路,找到resources/app/scripts/controllers/identity.js 文件,把 FlowServiceV1 改成 FlowServiceV2,修改后源码如下:
3.修改保持流控规则接口,在 identity.js 文件中,找到 saveFlowRule 方法进行改动,把 /dashboard/flow/ 换成 /dashboard/v2/flow/,修改后源码如下:
项目准备
1.引入 Sentinel 和 Nacos 依赖,如下:
<!--引入 Nacos 支持-->
<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId><version>2021.1</version>
</dependency><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId><version>2021.1</version>
</dependency><!--引入 sentinel 支持-->
<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-sentinel</artifactId><version>2021.1</version>
</dependency><dependency><groupId>com.alibaba.csp</groupId><artifactId>sentinel-datasource-nacos</artifactId><version>1.8.0</version>
</dependency>
文末会附上完整的 pom.xml 文件。
2.bootstrap.properties 中的 Nacos 和 Sentinel 配置如下:
#服务名称
spring.application.name=order-service
#服务端口
server.port=8081
#区分不同环境的配置文件
spring.profiles.active=dev
#nacos 账号密码
spring.cloud.nacos.username=nacos
spring.cloud.nacos.password=nacos
#nacos 地址
spring.cloud.nacos.server-addr=127.0.0.1:8848
#名称空间 默认 public
spring.cloud.nacos.discovery.namespace=sentinel#命名空间 ID 用于区分不同环境和应用 默认的 public 空间时候无需配置(或者直接留空即可) 否侧配置中心不生效
#spring.cloud.nacos.config.namespace=d5a53ce5-4288-401f-a748-f5c79bbd3ab3
spring.cloud.nacos.config.namespace=9bd69b59-f311-4f34-81c3-aaa4314dfbeb
#配置分组 默认即可 也可以自定义分组
spring.cloud.nacos.config.group=DEFAULT_GROUP
#默认为 spring.application.name 的值 也可以通过配置项 spring.cloud.nacos.config.prefix 来配置
spring.cloud.nacos.config.prefix=my-study-spring-boot
#配置名称 首先使用配置的前缀 然后再使用名称 最后使用 spring.application.name
spring.cloud.nacos.config.name=my-study-spring-boot
#配置文件格式后缀 默认为 properties
spring.cloud.nacos.config.file-extension=properties
#用于控制是否启用配置刷新功能 默认为true
spring.cloud.nacos.config.refresh-enabled=true
#配置拉取长轮询超时时间 单位为毫秒 默认为 30000 毫秒
spring.cloud.nacos.config.timeout=3000#sentinel dashboard 地址
spring.cloud.sentinel.transport.dashboard=localhost:8080
spring.cloud.sentinel.transport.port=8719
#Nacos 地址
spring.cloud.sentinel.datasource.flow.nacos.server-addr=127.0.0.1:8848
#spring.cloud.sentinel.datasource.flow.nacos.namespace=9bd69b59-f311-4f34-81c3-aaa4314dfbeb
#这里的这个配置没有生效 目前还没有搞清楚为啥不生效 欢迎各位老大指导
spring.cloud.sentinel.datasource.flow.nacos.namespace=sentinel
#生产的规则文件名称
spring.cloud.sentinel.datasource.flow.nacos.data-id=${spring.application.name}-flow-rules
#group id 默认 SENTINEL_GROUP
spring.cloud.sentinel.datasource.flow.nacos.group-id=SENTINEL_GROUP
#配置数据格式 使用 json
spring.cloud.sentinel.datasource.flow.nacos.data-type=json
# 规则类型 degrade、authority、param-flow
spring.cloud.sentinel.datasource.flow.nacos.rule-type=flow
Sentinel 流控规则验证
- 启动 Nocos 服务。
- 启动 Sentinel Dashboard。
- 启动 order-service 服务。
- 创建流控规则如下:
- Nacos 配置中心规则如下:
至此,Sentinel 规则持久化到 Nacos 已经完成,我们从 Sentinel 控制台创建的规则会持久化到 Nacos 中,我们在 Nacos 中修改规则也可以直接在 Sentinel 上看到。
未解之谜
不同应用服务的流控规则想持久化到 Nacos 的不同 Namespace 下如何实现?
多次尝试,发现如下配置不生效。
#这里的这个配置没有生效 目前还没有搞清楚为啥不生效 欢迎各位老大指导
spring.cloud.sentinel.datasource.flow.nacos.namespace=sentinel
如果不在 Sentinel Dashboard 中指定 Nacos Namespace,Sentinel 的流控规则将会默认在 public 名称空间下,在 Sentinel Dashboard 中指定 Nacos Namespace 配置,则所有应用的流控规则都会到同一个 Namespace 下了。
所以如何实现不同应用服务的流控规则持久化到 Nacos 的不同 Namespace?
最后附上 order-service 的完整 pom.xml 文件,如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.4.5</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.order.service</groupId><artifactId>order-service</artifactId><version>0.0.1-SNAPSHOT</version><name>order-service</name><description>order-service</description><url/><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency><!--引入 Nacos 支持--><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId><version>2021.1</version></dependency><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId><version>2021.1</version></dependency><!--引入 sentinel 支持--><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-sentinel</artifactId><version>2021.1</version></dependency><dependency><groupId>com.alibaba.csp</groupId><artifactId>sentinel-datasource-nacos</artifactId><version>1.8.0</version></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-bootstrap</artifactId><version>3.0.0</version></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-commons</artifactId><version>2.2.2.RELEASE</version><scope>compile</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
总结:本篇分享了如何使用 Nacos 持久化 Sentinel 规则,Nacos 提供了注册中心和配置中心的能力,是微服务技术栈中不可或缺的组件,因此建议使用 Nacos 来持久化 Sentinel 规则。
如有不正确的地方请各位指出纠正。