您当前的位置: 首页 >  spring

SpringCloudAlibaba之Sentinel-规则管理及推送模式(pull&push)

发布时间:2020-10-08 21:11:59 ,浏览量:0

相关代码

1 拉(pull)模式 1.1 架构设计

该模式的数据源(如本地文件、RDBMS 等)一般可写入。使用时需在客户端注册数据源:将对应读数据源注册至对应的RuleManager,将写数据源注册至transport的WritableDataSourceRegistry中。

以本地文件数据源为例:

public class FileDataSourceInit implements InitFunc { @Override public void init() throws Exception { String flowRulePath = "xxx"; ReadableDataSource<String, List<FlowRule>> ds = new FileRefreshableDataSource<>( flowRulePath, source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {}) ); // 将可读数据源注册至 FlowRuleManager. FlowRuleManager.register2Property(ds.getProperty()); WritableDataSource<List<FlowRule>> wds = new FileWritableDataSource<>(flowRulePath, this::encodeJson); // 将可写数据源注册至 transport 模块的 WritableDataSourceRegistry 中. // 这样收到控制台推送的规则时,Sentinel 会先更新到内存,然后将规则写入到文件中. WritableDataSourceRegistry.registerFlowDataSource(wds); } private <T> String encodeJson(T t) { return JSON.toJSONString(t); } } 

本地文件数据源会定时轮询文件的变更,读取规则。这样我们既可以在应用本地直接修改文件来更新规则,也可以通过 Sentinel 控制台推送规则。以本地文件数据源为例,推送过程如下图所示:

1.2 执行流程
  • FileRefreshableDataSource定时从指定文件中读取规则JSON文件【上图:本地文件】,如果发现文件发生变化,就更新规则缓存。
  • FileWritableDataSource接收控制台规则推送,并根据配置,修改规则JSON文件【图中的本地文件】。
1.3 代码实战 1.3.1 添加依赖
<dependency> <groupId>com.alibaba.cspspring.application.name}-flow-rules groupId: SENTINEL_GROUP # 规则类型,取值见: # org.springframework.cloud.alibaba.sentinel.datasource.RuleType rule-type: flow degrade: nacos: server-addr: localhost:8848 dataId: ${spring.application.name}-degrade-rules groupId: SENTINEL_GROUP rule-type: degrade system: nacos: server-addr: localhost:8848 dataId: ${spring.application.name}-system-rules groupId: SENTINEL_GROUP rule-type: system authority: nacos: server-addr: localhost:8848 dataId: ${spring.application.name}-authority-rules groupId: SENTINEL_GROUP rule-type: authority param-flow: nacos: server-addr: localhost:8848 dataId: ${spring.application.name}-param-flow-rules groupId: SENTINEL_GROUP rule-type: param-flow

重启服务

生产环境使用Sentinel

◆ 推拉模式持久化规则

  • 推模式更佳

◆ AHAS

  • 开通地址 https://ahas.console.aliyun.com/
  • 开通说明 https://help.aliyun.com/document detail/90323.html

参考

  • 在生产环境中使用-Sentinel
关注
打赏
1688896170
查看更多评论

暂无认证

  • 0浏览

    0关注

    115984博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.0434s