前言

在我们使用Sentinel做熔断限流等操作时,一些设置好的配置默认是存放在当前服的内存中的,那么也就意味着每次重启服务,这些配置好的配置就会消失。在我们搭建微服务架构做测试的时候不是很友好。大家都知道Sentinel提供了一些持久化方式,如持久化到Nacos、本地JSON文件。这种方式虽然能解决持久化的操作,但是不能自动同步更新,也就是持久化配置写成什么样就是什么样,在程序启动后,无法动态更新到持久化存储中!当然能做到持久化Nacos或者本地JSON已经很不错了!如果作用做到这一步那么请见Sentinel整合Nacos做持久化这篇文章就够了,如果想要更加灵活,想在运行过程中动态同步Nacos那么就请往下看!一键获取springcloud资料

Sentinel动态推拉数据持久化同步到Nacos

这个操作字面意思看似只要同步Nacos这一套逻辑,其实并不是,同步Nacos其实分为普通服务同步Nacos和Gateway同步Nacos。因为二者无论是在Sentinel
Datasource(Sentinel服务端)
还是我们自己的业务服(包括网关和其他服)通知拉取推送机制都是不一样的,所以针对这种情况需要做两手逻辑操作!

在写动态拉取数据持久化Nacos前,先保证普通服务整合Sentinel和Gateway整合Sentinel默认流程先能跑通!

Sentinel动态推拉数据持久化同步到Nacos(通用部分)

1.下载Sentinel源码

Sentinel-GitHub

我这里以1.7.1版本为基准,说到版本,这里我要多提一嘴,微服务架构搭建最恶心的我觉得倒不是代码有多难写,往往是代码没什么问题,总是各种版本对不上,这就比较头痛,不过我这里提供一套方案,这套版本适配的方案是比较准的,能帮我们确定一个版本的请款下适配Spring Boot、Spring Cloud、Spring Cloud Alibaba之间的版本版本说明,我整套微服务架构的版本使用的是Spring Boot 2.3.2.RELEASE、Spring Cloud Alibaba 2.2.5.RELEASE、Spring Cloud Hoxton.SR8

不扯远了,收回来接着本文继续搞重点!

这就是我们要二开的源码,idea打开一下

2.修改pom.xml

修改pom.xml中的sentinel-datasource-nacos的依赖,将test注释掉,这样才能在主程序中使用。

<dependency><groupId>com.alibaba.csp</groupId><artifactId>sentinel-datasource-nacos</artifactId><!--<scope>test</scope>-->
</dependency>


3.创建nacossync目录用来编写我们二开的代码

图中nacossync中这些类就是我们要编写的代码!

4.Naocs数据同步Properties映射类

这个类无论是Gateway二开同步还是普通服务二开都是公用的/*** @author TAO* @description: Naocs数据同步Properties映射类* @date 2021/5/1 22:36*/
@Component
@ConfigurationProperties(prefix = "nacos.server")
public class NacosConfigProperties {private String ip;private String port;private String namespace;private String groupId;public String getIp() {return ip;}public void setIp(String ip) {this.ip = ip;}public String getPort() {return port;}public void setPort(String port) {this.port = port;}public String getNamespace() {return namespace;}public void setNamespace(String namespace) {this.namespace = namespace;}public String getGroupId() {return groupId;}public void setGroupId(String groupId) {this.groupId = groupId;}public String getServerAddr() {return this.getIp() + ":" + this.getPort();}@Overridepublic String toString() {return "NacosConfigProperties [ip=" + ip + ", port=" + port + ", namespace="+ namespace + ", groupId=" + groupId + "]";}}

5.Nacos同步常量类

这个类可有可无,就看要不要这么规范

/*** @author TAO* @description: Nacos同步常量类* @date 2021/5/6 23:19*/
public final class NacosConfigConstant {public static final String FLOW_DATA_ID_POSTFIX = "-sentinel-flow";//统一sentinel持久化Nacos的文件后缀
}

6.Nacos同步配置类

这个类的话先写一个空类,后面写到具体的实现时我们在加对应代码!

/*** @author TAO* @description: Nacos同步配置类* @date 2021/5/6 23:19*/
@Configuration
public class NacosConfig {@Autowiredprivate NacosConfigProperties nacosConfigProperties;/***  TODO 非常关键 这里将FlowRuleEntity转换成FlowRule才会对客户端生效,一下几对是不同场景的版解码器,*  TODO 实际上就是将Nacos中的JSON解析为对应的实体类,将对应的实体类解析为JSON存储的* @return FlowRule*///TODO 后续这里会加对应的Bean代码 注意!@Beanpublic ConfigService nacosConfigService() throws Exception {Properties properties = new Properties();properties.put(PropertyKeyConst.SERVER_ADDR, nacosConfigProperties.getServerAddr());properties.put(PropertyKeyConst.NAMESPACE, nacosConfigProperties.getNamespace());return ConfigFactory.createConfigService(properties);}
}

7.application.properties配置文件,添加Nacos配置

注意namespace这个Nacos命名空间这个如果使用publish可以不写,如果是其他自建的namespace那么除了写namespace之外还要加其他的标识信息,这个我没深入研究

nacos.server.ip=nacos-ip
nacos.server.port=8848
nacos.server.namespace=
nacos.server.group-id=DEFAULT_GROUP

8.我们自己的业务服添加一下依赖

<!--sentinel-->
<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency><!--sentinel-nacos持久化-->
<dependency><groupId>com.alibaba.csp</groupId><artifactId>sentinel-datasource-nacos</artifactId>
</dependency>

9.我们自己的业务服添加一下配置

这段配置其实在做持久化Nacos时应该都写上了,这里还是提一嘴!

spring:application:name: yy-authcloud:nacos:discovery:server-addr: nacos:8848sentinel:transport:dashboard: sentinel:9999client-ip: 192.168.1.109 # 防止sentinel抓取虚拟ipport: 8719datasource: #注意虽然sentinel配置了同步nacos拓展,并且数据能在控制台上同步显示,但是那些数据只是控制台读取的,并不是我们自己真实的服务读取的,所以下面配置还要写ds1:nacos:server-addr: nacos:8848#namespace: sentineldataId: yy-auth-sentinel-flowgroupId: DEFAULT_GROUPdata-type: jsonrule-type: flow

Sentinel动态推拉数据持久化同步到Nacos(普通服务)

1.编写拉取Nacos配置类

/*** @author TAO* @description: 拉取Nacos配置* @date 2021/5/6 23:18*/
@Component("flowRuleNacosProvider")
public class FlowRuleNacosProvider implements DynamicRuleProvider<List<FlowRuleEntity>> {private static Logger logger = LoggerFactory.getLogger(FlowRuleNacosProvider.class);@Autowiredprivate NacosConfigProperties nacosConfigProperties;@Autowiredprivate ConfigService configService;@Autowiredprivate Converter<String, List<FlowRuleEntity>> converter;@Overridepublic List<FlowRuleEntity> getRules(String appName) throws Exception {logger.info("当前从Nacos中拉取的限流规则配置文件名:{}", appName + NacosConfigConstant.FLOW_DATA_ID_POSTFIX);String rules = configService.getConfig(appName + NacosConfigConstant.FLOW_DATA_ID_POSTFIX, nacosConfigProperties.getGroupId(), 3000);logger.info("从Nacos中拉取到限流规则信息:{}", rules);if (StringUtil.isEmpty(rules)) {return new ArrayList<>();}return converter.convert(rules);}
}

2.编写推送配置到Nacos类

/*** @author TAO* @description: 推送配置到Nacos* @date 2021/5/6 23:19*/
@Component("flowRuleNacosPublisher")
public class FlowRuleNacosPublisher implements DynamicRulePublisher<List<FlowRuleEntity>> {private static Logger logger = LoggerFactory.getLogger(FlowRuleNacosPublisher.class);@Autowiredprivate NacosConfigProperties nacosConfigProperties;@Autowiredprivate ConfigService configService;@Autowiredprivate Converter<List<FlowRuleEntity>, String> converter;@Overridepublic void publish(String app, List<FlowRuleEntity> rules) throws Exception {AssertUtil.notEmpty(app, "app name cannot be empty");if (rules == null) {return;}logger.info("推送到Nacos配置:{}", rules);configService.publishConfig(app + NacosConfigConstant.FLOW_DATA_ID_POSTFIX, nacosConfigProperties.getGroupId(), converter.convert(rules));}
}

3.修改流控规则跳转URL

找到resources/app/scripts/directives/sidebar/sidebar.html中的这段代码:

<li ui-sref-active="active"><a ui-sref="dashboard.flowV1({app: entry.app})"><i class="glyphicon glyphicon-filter"></i>&nbsp;&nbsp;流控规则</a>
</li>

修改为:

<li ui-sref-active="active"><a ui-sref="dashboard.flow({app: entry.app})"><i class="glyphicon glyphicon-filter"></i>&nbsp;&nbsp;流控规则</a>
</li>

这样修改之后就会跳转到FlowControllerV2的接口。

4.在Nacos同步配置类中添加对应Bean

//普通服务-Sentinel同步Nacos@Beanpublic Converter<List<FlowRuleEntity>, String> flowRuleEntityEncoder() {return rules -> JSON.toJSONString(rules.stream().map(FlowRuleEntity::toRule).collect(Collectors.toList()), true);}@Beanpublic Converter<String, List<FlowRuleEntity>> flowRuleEntityDecoder() {return s -> JSON.parseArray(s, FlowRuleEntity.class);}

5.将flowRuleDefaultProvider、flowRuleDefaultPublisher替换为我们自己的flowRuleNacosProvider、flowRuleNacosPublisher
将FlowControllerV2中的默认DynamicRuleProvider和DynamicRulePublisher修改为:

@Autowired
@Qualifier("flowRuleNacosProvider")
private DynamicRuleProvider<List<FlowRuleEntity>> ruleProvider;
@Autowired
@Qualifier("flowRuleNacosPublisher")
private DynamicRulePublisher<List<FlowRuleEntity>> rulePublisher;private void publishRules(/*@NonNull*/ String app) throws Exception {List<FlowRuleEntity> rules = repository.findAllByApp(app);rulePublisher.publish(app, rules);logger.info("添加限流规则成功{}", JSON.toJSONString(rules.stream().map(FlowRuleEntity::toRule).collect(Collectors.toList()), true));
}

重启服务即可!注意,我这里直接修改的是导航栏的跳转URL,所以只有在对应位置才有效

其他入口需要修改才生效。这里我就不过多演示了!

Sentinel动态推拉数据持久化同步到Nacos(Gateway)
Gateway做推拉持久化就更加简单了!废话不都说,干就完事了!

1.编写拉取Nacos-Gateway配置

/*** @author TAO* @description: 拉取Nacos-Gateway配置* @date 2021/5/6 23:18*/
@Component("flowRuleNacosGatewayProvider")
public class FlowRuleNacosGatewatProvider implements DynamicRuleProvider<List<GatewayFlowRuleEntity>> {private static Logger logger = LoggerFactory.getLogger(FlowRuleNacosGatewatProvider.class);@Autowiredprivate NacosConfigProperties nacosConfigProperties;@Autowiredprivate ConfigService configService;@Autowiredprivate Converter<String, List<GatewayFlowRuleEntity>> converter;@Overridepublic List<GatewayFlowRuleEntity> getRules(String appName) throws Exception {logger.info("当前从Nacos中拉取Gateway的限流规则配置文件名:{}", appName + NacosConfigConstant.FLOW_DATA_ID_POSTFIX);String rules = configService.getConfig(appName + NacosConfigConstant.FLOW_DATA_ID_POSTFIX, nacosConfigProperties.getGroupId(), 3000);logger.info("从Nacos中拉取到Gateway限流规则信息:{}", rules);if (StringUtil.isEmpty(rules)) {return new ArrayList<>();}return converter.convert(rules);}
}

2.编写推送配置到Nacos-Gateway

/*** @author TAO* @description: 推送配置到Nacos-Gateway* @date 2021/5/6 23:19*/
@Component("flowRuleNacosGatewayPublisher")
public class FlowRuleNacosGatewayPublisher implements DynamicRulePublisher<List<GatewayFlowRuleEntity>> {private static Logger logger = LoggerFactory.getLogger(FlowRuleNacosGatewayPublisher.class);@Autowiredprivate NacosConfigProperties nacosConfigProperties;@Autowiredprivate ConfigService configService;@Autowiredprivate Converter<List<GatewayFlowRuleEntity>, String> converter;@Overridepublic void publish(String app, List<GatewayFlowRuleEntity> rules) throws Exception {AssertUtil.notEmpty(app, "app name cannot be empty");if (rules == null) {return;}logger.info("推送到Gateway-Nacos配置:{}", rules);configService.publishConfig(app + NacosConfigConstant.FLOW_DATA_ID_POSTFIX, nacosConfigProperties.getGroupId(), converter.convert(rules));}
}

3.Nacos同步配置类添加相应Bean

//Gateway-Sentinel同步Nacos@Beanpublic Converter<List<GatewayFlowRuleEntity>, String> gatewayFlowRuleEntityEncoder() {return rules -> JSON.toJSONString(rules);}@Beanpublic Converter<String, List<GatewayFlowRuleEntity>> gatewayFlowRuleEntityDecoder() {return s -> JSON.parseArray(s, GatewayFlowRuleEntity.class);}

4.Gateway服务pom添加相应依赖

<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!--sentinel-gateway-->
<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency><!--sentinel-nacos持久化-->
<dependency><groupId>com.alibaba.csp</groupId><artifactId>sentinel-datasource-nacos</artifactId>
</dependency><dependency><groupId>com.alibaba.csp</groupId><artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>
</dependency>

5.Gateway服务添加配置

spring:application:name: yy-gatewaymain:allow-bean-definition-overriding: truecloud:nacos:discovery:server-addr: nacos:8848sentinel:transport:dashboard: sentinel:9999client-ip: 10.0.0.208 # 防止sentinel抓取虚拟ipport: 8719datasource: #注意虽然sentinel配置了同步nacos拓展,并且数据能在控制台上同步显示,但是那些数据只是控制台读取的,并不是我们自己真实的服务读取的,所以下面配置还要写ds1:nacos:server-addr: nacos:8848#namespace: sentineldataId: yy-gateway-sentinel-flowgroupId: DEFAULT_GROUPdata-type: jsonrule-type: gw-flow

这里注意一下rule-type和普通服务不一样, gw-flow,重启服务即可!

Sentinel动态推拉数据持久化同步到Nacos相关推荐

  1. Sentinel Dashboard 中修改规则同步到 Nacos

    点击蓝色"程序猿DD"关注我哟 加个"星标",不忘签到哦 上一篇我们介绍了如何通过改造Sentinel Dashboard来实现修改规则之后自动同步到Apoll ...

  2. sentinel限流规则持久化改造,nacos数据源拉取、推送双向同步

    sentinel的功能强大,官方也提供了包括数据库.redis.nacos等多种数据源实现持久化动态规则,还提供了sentinel-dashboard的可视化界面配置规则 但是实际使用中发现,官方的可 ...

  3. 限流神器Sentinel与nacos数据双向同步

    sentinel与springcloud.spring cload alibaba 版本选择 版本参考: 版本说明 · alibaba/spring-cloud-alibaba Wiki · GitH ...

  4. rsync推拉模型及结合inotify实现推模型自动同步

    一.前言 无论使用什么操作系统下,都经常有同步文件的需求,不管发生在本地,还是发生在本地和远程主机之间.那么应该怎么做呢? 使用拷贝类的命令,本地使用cp命令,复制到远程主机使用scp这样的命令,保证 ...

  5. F9-sersync推送数据rsync拉取数据

    1.基于三台服务器,部署数据实时同步服务器,一台作为主服务器sersync(推送数据),其余两台作为备用服务器rsync(拉取数据): (1)先配置sersync <1>安装包sersyn ...

  6. SpringCloudAlibaba 六、Sentinel 服务保护 ( 服务降级/ 熔断/ 数据持久化 / gateway 整合 Sentinel )

    一.Sentinel 描叙 1.Sentinel作用 Sentinel,中文翻译为哨兵,是为微服务提供流量控制.熔断降级的功能,它和Hystrix提供的功能一样,可以有效的解决微服务调用产生的&quo ...

  7. Python Scrapy 爬虫框架爬取推特信息及数据持久化!整理了我三天!

    最近要做一个国内外新冠疫情的热点信息的收集系统,所以,需要爬取推特上的一些数据,然后做数据分类及情绪分析.作为一名合格的程序员,我们要有「拿来主义精神」,借助别人的轮子来实现自己的项目,而不是从头搭建 ...

  8. sentinel 官方文档_Sentinel控制台监控数据持久化到MySQL数据库

    阅读文本大概需要3分钟. 根据官方wiki文档,Sentinel控制台的实时监控数据,默认仅存储 5 分钟以内的数据.如需持久化,需要定制实现相关接口. https://github.com/alib ...

  9. k8s mysql数据同步_K8s——MySQL实现数据持久化

    1.搭建nfs存储 [root@docker-k8s01 ~]# yum -y install nfs-utils [root@docker-k8s01 ~]# mkdir /nfsdata/mysq ...

最新文章

  1. Linux下 apache 配置 wsgi 以使用 python-flask (2016年2月)
  2. 利用机器学习算法对实验室小鼠的睡眠阶段自动分类
  3. 谈谈Javascript闭包
  4. django媒体文件上传设置
  5. vnc用户名 查看linux_vnc用户名未被识别,5步教你如何解决vnc用户名未被识别
  6. Java Integer类toString()方法与示例
  7. matlab出错及解决办法,Linux下使用Matlab符号函数出错的解决办法
  8. 使用js实现思维导图
  9. vxetable显示html,vxe-table分页无法显示?
  10. 在ubuntu14.04中安装gazebo
  11. $mona$要成为高端玩家
  12. mac实用小技巧分享之使Mac快速锁屏与睡眠
  13. android m壁纸驱动之家,微软打造的良心壁纸App,仅4.2M
  14. 百胜中国二次上市:肯德基与必胜客贡献九成营收,春华资本是股东
  15. android搜索app下载地址,如何找出APP的URL Scheme
  16. 模型导入unity贴图缺失怎么办?
  17. MathType 快捷键大全——数学建模神器yyds(告别繁杂的公式)
  18. 什么专业python工程师_西安专业的Python工程师哪家专业
  19. 网络爬虫框架——Scrapy框架解析
  20. python plt图片保存emf类型_如何获得emf/wmf格式的matplotlib图形?

热门文章

  1. Python基于YOLOv5的交通标志识别系统[源码]
  2. 数据挖掘系列(4)_Excel的数据挖掘插件_预测
  3. 栈与队列--小猫钓鱼(详解版)
  4. jforum mysql_JForum论坛安装以及部署(转)
  5. Java商品规格添加购物车_关于java+jsp购物车添加商品的有关问题,来哦
  6. 软件安全实验——pre6(整数溢出、堆溢出、栈溢出漏洞预习)
  7. 勤奋、乐观、皮实、自省
  8. idea调试需要的快捷键_IDEA调试常用快捷键
  9. 提升国际品牌影响力:小企业海外网红营销实战指南
  10. ubuntu下vsftpd配置详细篇