当前位置: 首页 > news >正文

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,并自动同步到所有客户端应用。

http://www.jsqmd.com/news/321931/

相关文章:

  • oracle表空间管理
  • 2026年1月内蒙古十大营销策划公司优选机构,技术+运营+效果全解析
  • 告别期刊投稿“修罗场”!虎贲等考AI用智能黑科技,让你的论文一次命中
  • AutoCAD 的二次开发
  • 亲测好用10个AI论文软件,助你轻松搞定本科生论文!
  • 瑞幸前端开发二面 28k前端面试全程记录
  • 探秘锅圈盈利预告,最高92%增长背后有何过人之处?
  • 基于springboot的校园智能物流管理系统
  • Java计算机毕设之基于SpringBoot的社区帮扶邻里服务平台社区邻里服务平台设计与实现(完整前后端代码+说明文档+LW,调试定制等)
  • 【遥感应用技术科普】基于多时相数据的耕地撂荒遥感监测
  • 2026年烟台营销推广公司专项甄选报告:头部优质机构全景梳理及专业选型指南
  • 2026年郑州营销策划公司推荐:本地企业增长痛点深度评测与权威排名解析
  • 京东e卡(电子卡)回收推荐两家平台
  • 二叉树--所有路径
  • 手把手教会你什么是 Java 多态 —— 从“if-else 地狱”到“一行代码搞定”(Spring Boot 实战)
  • 2026年西安营销推广公司推荐:权威榜单揭晓,品帮科技领跑
  • 让销售团队产能实现翻番的秘密武器:从进行海量筛选转变为能够一键直连老板
  • 2026年郑州营销策划公司推荐:基于技术整合能力评测,针对数字化转型与效果衡量痛点
  • 十大家装品牌精选推荐:2026年1月厦门家装公司排行榜单
  • Thrombin (B 147-158) (human) ;TWTANVGKGQPS
  • 轻松同步 Outlook 联系人到 Android
  • 2026年长沙营销推广公司权威评测:基于实战效果的五家头部企业深度解析
  • 数字广播调制器 纽格立NGA-201 DRM-FM调频广播调制器调频数字广播改造适用
  • Java毕设项目:基于SpringBoot的社区邻里服务平台设计与实现(源码+文档,讲解、调试运行,定制等)
  • 使用 6 种方法将文件从 Android 无缝传输到iPad
  • 2026年内蒙古营销策划公司推荐:基于技术特性与本地服务评测,涵盖线上线下多场景运营痛点。
  • 2026年郑州营销策划公司推荐:全域智能营销排名,解决预算有限与效果不彰痛点
  • 2026年长沙营销推广公司推荐 | 基于10大核心指标解析
  • 2026年郑州营销策划公司推荐:基于多行业场景深度评测,解决增长与品牌协同核心痛点并附排名
  • 创客匠人伦理深研:知识变现中的数据安全与AI智能体边界——构建可信、可持续的知识服务生态