【微服务与分布式实践】探索 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 来集中管理和推送规则,实现规则的持久化和实时更新。这样,即使服务重启,配置的规则也不会丢失,并且可以快速响应规则的变化。

相关推荐
一条懒鱼66612 小时前
Redis Sentinel哨兵集群
数据库·redis·sentinel
2301_797604241 天前
d44:Sentinel 微服务流量控制与 Seata 分布式事务
分布式·微服务·sentinel
新手小白*1 天前
Redis Sentinel哨兵集群
数据库·redis·sentinel
来一杯龙舌兰5 天前
【Sentinel】Springboot整合Sentinel、Socket进行熔断限流(生产级熔断限流)
spring boot·后端·sentinel·熔断限流
kkkkk0211069 天前
微服务学习笔记(黑马商城)
java·spring boot·spring·spring cloud·sentinel·mybatis·java-rabbitmq
choice of10 天前
Sentinel:阿里云高并发流量控制
笔记·spring cloud·sentinel
W.Buffer12 天前
SpringCloud-Sentinel实战与源码分析:从流量防护到底层实现
spring·spring cloud·sentinel
TM_soul12 天前
Sentinel安装部署
sentinel
不能再留遗憾了15 天前
【SpringCloud】Sentinel
spring·spring cloud·sentinel
Chan1616 天前
流量安全优化:基于 Sentinel 实现网站流量控制和熔断
java·spring boot·安全·sentinel·intellij-idea·进程