news 2026/4/1 14:17:09

Sentinel Dashboard 与 Nacos 集成代码模板详解:实现流控规则持久化至 Nacos

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
Sentinel Dashboard 与 Nacos 集成代码模板详解:实现流控规则持久化至 Nacos

Sentinel Nacos 规则持久化代码解析

本文介绍 Sentinel Dashboard 集成 Nacos 作为动态规则配置中心的实现代码。

NacosConfig.java

/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */packagecom.alibaba.csp.sentinel.dashboard.rule.nacos;importjava.util.List;importcom.alibaba.csp.sentinel.dashboard.datasource.entity.rule.FlowRuleEntity;importcom.alibaba.csp.sentinel.datasource.Converter;importcom.alibaba.fastjson.JSON;importcom.alibaba.nacos.api.config.ConfigFactory;importcom.alibaba.nacos.api.config.ConfigService;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;/** * @author Eric Zhao * @since 1.4.0 */@ConfigurationpublicclassNacosConfig{@BeanpublicConverter<List<FlowRuleEntity>,String>flowRuleEntityEncoder(){returnJSON::toJSONString;}@BeanpublicConverter<String,List<FlowRuleEntity>>flowRuleEntityDecoder(){returns->JSON.parseArray(s,FlowRuleEntity.class);}@BeanpublicConfigServicenacosConfigService()throwsException{returnConfigFactory.createConfigService("localhost");}}

NacosConfigUtil.java

/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */packagecom.alibaba.csp.sentinel.dashboard.rule.nacos;/** * @author Eric Zhao * @since 1.4.0 */publicfinalclassNacosConfigUtil{publicstaticfinalStringGROUP_ID="SENTINEL_GROUP";publicstaticfinalStringFLOW_DATA_ID_POSTFIX="-flow-rules";publicstaticfinalStringPARAM_FLOW_DATA_ID_POSTFIX="-param-rules";publicstaticfinalStringCLUSTER_MAP_DATA_ID_POSTFIX="-cluster-map";/** * cc for `cluster-client` */publicstaticfinalStringCLIENT_CONFIG_DATA_ID_POSTFIX="-cc-config";/** * cs for `cluster-server` */publicstaticfinalStringSERVER_TRANSPORT_CONFIG_DATA_ID_POSTFIX="-cs-transport-config";publicstaticfinalStringSERVER_FLOW_CONFIG_DATA_ID_POSTFIX="-cs-flow-config";publicstaticfinalStringSERVER_NAMESPACE_SET_DATA_ID_POSTFIX="-cs-namespace-set";privateNacosConfigUtil(){}}

FlowRuleNacosPublisher.java

/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */packagecom.alibaba.csp.sentinel.dashboard.rule.nacos;importjava.util.List;importcom.alibaba.csp.sentinel.dashboard.datasource.entity.rule.FlowRuleEntity;importcom.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher;importcom.alibaba.csp.sentinel.datasource.Converter;importcom.alibaba.csp.sentinel.util.AssertUtil;importcom.alibaba.nacos.api.config.ConfigService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Component;/** * @author Eric Zhao * @since 1.4.0 */@Component("flowRuleNacosPublisher")publicclassFlowRuleNacosPublisherimplementsDynamicRulePublisher<List<FlowRuleEntity>>{@AutowiredprivateConfigServiceconfigService;@AutowiredprivateConverter<List<FlowRuleEntity>,String>converter;@Overridepublicvoidpublish(Stringapp,List<FlowRuleEntity>rules)throwsException{AssertUtil.notEmpty(app,"app name cannot be empty");if(rules==null){return;}configService.publishConfig(app+NacosConfigUtil.FLOW_DATA_ID_POSTFIX,NacosConfigUtil.GROUP_ID,converter.convert(rules));}}

FlowRuleNacosProvider.java

/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */packagecom.alibaba.csp.sentinel.dashboard.rule.nacos;importjava.util.ArrayList;importjava.util.List;importcom.alibaba.csp.sentinel.dashboard.datasource.entity.rule.FlowRuleEntity;importcom.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider;importcom.alibaba.csp.sentinel.datasource.Converter;importcom.alibaba.csp.sentinel.util.StringUtil;importcom.alibaba.nacos.api.config.ConfigService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Component;/** * @author Eric Zhao * @since 1.4.0 */@Component("flowRuleNacosProvider")publicclassFlowRuleNacosProviderimplementsDynamicRuleProvider<List<FlowRuleEntity>>{@AutowiredprivateConfigServiceconfigService;@AutowiredprivateConverter<String,List<FlowRuleEntity>>converter;@OverridepublicList<FlowRuleEntity>getRules(StringappName)throwsException{Stringrules=configService.getConfig(appName+NacosConfigUtil.FLOW_DATA_ID_POSTFIX,NacosConfigUtil.GROUP_ID,3000);if(StringUtil.isEmpty(rules)){returnnewArrayList<>();}returnconverter.convert(rules);}}

1.NacosConfigUtil.java- 配置常量类

这是一个工具类,定义了 Nacos 中存储 Sentinel 规则的命名规范。

核心常量:

GROUP_ID="SENTINEL_GROUP"// Nacos 配置分组

Data ID 后缀规范:

后缀用途示例
-flow-rules流控规则myapp-flow-rules
-param-rules热点参数规则myapp-param-rules
-cluster-map集群映射配置myapp-cluster-map
-cc-config集群客户端配置myapp-cc-config
-cs-transport-config集群服务端传输配置myapp-cs-transport-config
-cs-flow-config集群服务端流控配置myapp-cs-flow-config
-cs-namespace-set集群服务端命名空间集myapp-cs-namespace-set

作用:统一管理 Nacos 配置的命名规则,避免硬编码。


2.NacosConfig.java- Spring 配置类

这是 Spring Boot 配置类,用于创建 Nacos 相关的 Bean。

三个关键 Bean:

flowRuleEntityEncoder- 规则编码器
returnJSON::toJSONString;
  • List<FlowRuleEntity>转换为 JSON 字符串
  • 用于发布规则到 Nacos 时序列化
flowRuleEntityDecoder- 规则解码器
returns->JSON.parseArray(s,FlowRuleEntity.class);
  • 将 JSON 字符串解析为List<FlowRuleEntity>
  • 用于从 Nacos 读取规则时反序列化
nacosConfigService- Nacos 客户端
ConfigFactory.createConfigService("localhost");
  • 创建 Nacos ConfigService 实例
  • 注意:这里硬编码了localhost,生产环境需要改为实际的 Nacos 地址

3.FlowRuleNacosPublisher.java- 规则发布器

实现DynamicRulePublisher接口,负责将流控规则推送到 Nacos

核心方法:

publicvoidpublish(Stringapp,List<FlowRuleEntity>rules)throwsException{AssertUtil.notEmpty(app,"app name cannot be empty");if(rules==null){return;}configService.publishConfig(app+NacosConfigUtil.FLOW_DATA_ID_POSTFIX,// Data ID: myapp-flow-rulesNacosConfigUtil.GROUP_ID,// Group: SENTINEL_GROUPconverter.convert(rules)// 转换为 JSON);}

执行流程:

  1. 校验app 名称不为空
  2. 构造 Data ID:应用名 +-flow-rules
  3. 序列化规则:通过converter将规则列表转为 JSON
  4. 发布配置:调用 Nacos API 发布到指定分组

使用场景:

  • Dashboard 页面修改流控规则时
  • 规则保存到 Nacos 持久化

4.FlowRuleNacosProvider.java- 规则提供器

实现DynamicRuleProvider接口,负责从 Nacos 拉取流控规则

核心方法:

publicList<FlowRuleEntity>getRules(StringappName)throwsException{Stringrules=configService.getConfig(appName+NacosConfigUtil.FLOW_DATA_ID_POSTFIX,// Data IDNacosConfigUtil.GROUP_ID,// Group3000// 超时 3 秒);if(StringUtil.isEmpty(rules)){returnnewArrayList<>();// 无配置返回空列表}returnconverter.convert(rules);// 反序列化}

执行流程:

  1. 从 Nacos 获取配置:根据 Data ID 和 Group 查询
  2. 检查空值:如果配置为空,返回空列表
  3. 反序列化:将 JSON 字符串解析为规则对象列表

使用场景:

  • Dashboard 启动时加载规则
  • 页面刷新时重新拉取规则

架构设计亮点

1.解耦设计

Publisher (发布) ←→ Nacos ←→ Provider (拉取)
  • 读写分离,职责清晰
  • 通过接口定义,易于扩展到其他配置中心(Apollo、Consul 等)

2.转换器模式

Converter<List<FlowRuleEntity>,String>// 编码Converter<String,List<FlowRuleEntity>>// 解码
  • 统一序列化/反序列化逻辑
  • 可替换 JSON 实现(如换成 Jackson)

3.配置规范化

  • 通过NacosConfigUtil统一命名规则
  • 避免不同模块使用不同的 Data ID 规范

实际应用示例

在 Nacos 中的配置结构:

Data ID: myapp-flow-rules Group: SENTINEL_GROUP Content: [ { "resource": "/api/test", "limitApp": "default", "grade": 1, "count": 10, "strategy": 0, "controlBehavior": 0 } ]

Dashboard 使用流程:

  1. 用户在 Dashboard 修改规则
  2. 调用FlowRuleNacosPublisher.publish()推送到 Nacos
  3. Nacos 通知客户端应用(通过监听器)
  4. 客户端应用更新本地规则缓存
  5. Dashboard 通过FlowRuleNacosProvider.getRules()刷新显示

注意事项

⚠️ 需要修改的地方:

  1. Nacos 地址硬编码
// 生产环境需要改为:ConfigFactory.createConfigService("nacos-server:8848");
  1. 缺少命名空间配置
// 建议添加 namespace 隔离不同环境Propertiesproperties=newProperties();properties.put("serverAddr","localhost:8848");properties.put("namespace","dev");ConfigFactory.createConfigService(properties);
  1. 错误处理
  • 当前代码未处理 Nacos 连接失败的情况
  • 建议添加重试机制和降级策略

这套代码提供了 Sentinel 与 Nacos 集成的标准实现模板,是实现规则持久化的关键组件。通过这种设计,Dashboard 的规则修改可以持久化到 Nacos,并自动同步到所有客户端应用。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/3/26 23:53:43

计算机毕业设计之基于springboot的流浪动物救助管理系统设计与实现

伴随着我国社会的发展&#xff0c;人民生活质量日益提高。于是对流浪动物救助管理进行规范而严格是十分有必要的&#xff0c;所以许许多多的信息管理系统应运而生。此时单靠人力应对这些事务就显得有些力不从心了。所以本论文将设计一套基于springboot的流浪动物救助管理系统&a…

作者头像 李华
网站建设 2026/3/25 7:37:38

如何科学选择软件开发公司:需求匹配与实力评估全解析

在数字化转型浪潮中&#xff0c;软件已成为企业运营与增长的核心引擎。无论是构建客户触达平台、优化内部流程&#xff0c;还是开发创新产品&#xff0c;选择一家靠谱的软件开发公司都是项目成功的关键第一步。然而&#xff0c;面对市场上数量众多、宣传各异的服务商&#xff0…

作者头像 李华
网站建设 2026/3/25 0:52:03

如何用AI预测软件缺陷?2026年智能测试术

AI驱动软件测试的新纪元 软件缺陷预测正从经验依赖转向数据智能驱动。2026年&#xff0c;AI技术通过机器学习&#xff08;ML&#xff09;、深度学习&#xff08;DL&#xff09;和自然语言处理&#xff08;NLP&#xff09;重塑测试范式&#xff0c;实现从“事后修复”到“事前预…

作者头像 李华
网站建设 2026/3/22 21:17:32

制作小商家线上引流工具,生成适配线上引流方案(朋友圈/短视频),提供文案模板,帮小商家快速获客,提高爆光。

1. 实际应用场景与痛点分析场景描述- 小商家&#xff08;餐饮店、服装店、美甲店、培训机构等&#xff09;想要通过线上渠道吸引顾客&#xff0c;但&#xff1a;1. 不懂如何写朋友圈或短视频文案。2. 不了解不同平台的引流玩法。3. 没有现成的模板&#xff0c;每次都要从零开始…

作者头像 李华