【微服务与分布式实践】探索 Sentinel

参数设置

  • 熔断时长 、最小请求数、最大RT ms、比例阈值、异常数

熔断策略

  • 慢调⽤⽐例
    • 当单位统计时⻓内请求数⽬⼤于设置的最⼩请求数⽬,并且慢调⽤的⽐例⼤于阈值,则接下来的熔断时⻓内请求会⾃动被熔断
  • 异常⽐例
    • 当单位统计时⻓内请求数⽬⼤于设置的最⼩请求数⽬,并且异常的⽐例⼤于阈值,则接下来的熔断时⻓内请求会⾃动被熔断
  • 异常数
    • 当单位统计时⻓内的异常数⽬超过阈值之后会⾃动进⾏熔断
  • 熔断规则
    • 熔断条件
      • 接口异常率超过10%,或者慢调用(响应时间>3s)的比例大于20%,触发60s熔断
    • 熔断操作
      • 直接返回默认实现

ZooKeeper 作为配置中心

Sentinel 是阿里巴巴开源的一套服务容错框架,用于服务的流量控制、熔断和系统负载保护。Sentinel 可以通过多种方式动态配置规则,其中包括使用 ZooKeeper 作为配置中心来集中管理和推送规则。以下是 Sentinel 如何使用 ZooKeeper 的基本步骤和配置:

  1. 搭建 ZooKeeper 环境:
  • 启动 ZooKeeper 服务,可以使用 ZooKeeper 的常用命令来管理服务,例如启动 (sh bin/zkServer.sh start)、查看状态 (sh bin/zkServer.sh status)、停止 (sh bin/zkServer.sh stop) 和重启 (sh bin/zkServer.sh restart) 服务。
  1. 引入 ZooKeeper 依赖:
  • 在 Sentinel Dashboard 工程中引入 ZooKeeper 相关的依赖,例如使用 Apache Curator 客户端:

<dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-recipes</artifactId> <version>${curator.version}</version> </dependency>

注意去掉 test 标签,以便在非测试环境中使用。

  1. 同步规则到 ZooKeeper:
  • 在 Sentinel Dashboard 中,通过 ZooKeeper 同步流控规则和降级规则。需要指定 ZooKeeper 路径(zkpath)来存储规则信息,例如:

// 流控规则 final String flowPath = "/sentinel_rule_config/" + appName + "/flow"; // 降级规则 final String degradePath = "/sentinel_rule_config/" + appName + "/degrade";

其中 appName 是应用的名称。

  1. 修改 Controller:
  • 修改 Sentinel Dashboard 中的 Controller,以便在规则变更时通过 ZooKeeper 发送通知。这涉及到修改流控规则(FlowController)和降级规则(DegradeController)的 Controller。
  1. 客户端配置:
  • 在客户端项目中引入 Sentinel ZooKeeper 数据源依赖:

<dependency> <groupId>com.alibaba.csp</groupId> <artifactId>sentinel-datasource-zookeeper</artifactId> <version>${sentinel.version}</version> </dependency>

  • 创建 ZookeeperDataSource 实例并注册到对应的 RuleManager:

ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new ZookeeperDataSource<>(remoteAddress, path, source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {})); FlowRuleManager.register2Property(flowRuleDataSource.getProperty());

其中 remoteAddress 是 ZooKeeper 服务地址,path 是数据路径。

通过以上步骤,Sentinel 可以利用 ZooKeeper 来集中管理和推送规则,实现规则的持久化和实时更新。这样,即使服务重启,配置的规则也不会丢失,并且可以快速响应规则的变化。

相关推荐
码代码的小农3 小时前
深入浅出Sentinel:分布式系统的流量防卫兵
sentinel
搬砖天才、1 天前
日常记录-redis主从复制(master-slave)+ Sentinel 哨兵(高可用)
数据库·redis·sentinel
是赵敢敢啊1 天前
sentinel
sentinel
东阳马生架构2 天前
Sentinel源码—9.限流算法的实现对比二
算法·sentinel
东阳马生架构2 天前
Sentinel源码—9.限流算法的实现对比一
算法·sentinel
东阳马生架构3 天前
Sentinel源码—9.限流算法的实现对比
sentinel
东阳马生架构3 天前
Sentinel源码—7.参数限流和注解的实现二
java·sentinel
东阳马生架构3 天前
Sentinel源码—8.限流算法和设计模式总结一
算法·sentinel
东阳马生架构4 天前
Sentinel源码—8.限流算法和设计模式总结
sentinel
东阳马生架构5 天前
Sentinel源码—6.熔断降级和数据统计的实现二
java·sentinel