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

【SpringCloud】Hystrix、Resilience4j 简述

文章目录

  • Hystrix、Resilience4j简介
  • 服务熔断(Circuit Breaker)
    • 定义
    • 实现方式
      • 导入依赖
      • 配置熔断规则
      • 代码实现
    • Feign集成Resilience4j
  • 服务降级(Fallback)
    • 定义
    • 场景
      • 正常响应
      • 服务降级后相应
    • 实现方式
      • Feign 降级
      • `@CircuitBreaker`降级
  • Dashboard流监控(不会呀)
    • 定义
    • 实现方式
      • 启用 Actuator 端点
      • 集成 Micrometer + Prometheus
      • 配置 Prometheus 抓取数据
      • 使用Grafana可视化
        • 前提条件
        • 使用流程
  • 国内的SpringCloud Alibaba
    • 使用Sentinel Dashboard 的集成方案
    • SC Alibaba在2023年度 降本增效,好多项目都不维护了
    • SC K8s,需要团队中 有 特别牛的架构团队,不然成本太高。
    • 微服务并不一定是最好的,最优的,一定要选择最适合自己的

技术虽已迭代,思想却将留存,解决问题的思路和学习问题的想法不能被束缚。

持续学习中··· ···

Hystrix、Resilience4j简介

Hystrix同前面的Ribbon一样,已经是过去式了,当前的主流框架 变为SpringBoot 3.*时代的时候,已经更新为Resilience4j,同样是一款优秀的 微服务容错组件;

Hystrix 使用 Hystrix Dashboard + Turbine 进行可视化实时监控的内容;

Resilience4j 使用 Micrometer + Prometheus + Grafana 进行服务监控;

现在是服务熔断降级一体化。

服务熔断:调用端,消费端

  • 某个服务超时或者出现异常,会引起熔断

服务降级:消费端,客户端

  • 会从整个网站的负载考虑,当服务熔断或关闭之后,服务将不再被调用;
  • 在客户端做一个自己的失败回调,FallBackFactory,返回一个默认缺省值,整体服务下降;

服务熔断(Circuit Breaker)

定义

服务熔断 是一种自动保护机制:当某个服务调用失败率过高时,系统会“熔断”该链路,快速失败,避免请求堆积而导致雪崩

熔断的三种状态:

  1. Closed(闭合):正常调用,记录成功/失败次数;
  2. Open(打开):拒绝请求,不调用任何服务,快速返回错误或降级;
  3. Half-Open(半开合):允许少量请求试探,尝试恢复,若成功则恢复Closed,否则重回Open;

实现方式

Hystrix、Resilience4j 都是定义在服务消费方的,和RestClient关联的;

我的架构:

  • 8080 : 服务消费方
  • 700*:服务注册服务器
  • 8001:服务提供方

放到话,在8080的内容中进行实现。

导入依赖

<!-- Spring Cloud Circuit Breaker 抽象 -->
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-circuitbreaker-resilience4j</artifactId>
</dependency><!-- 可选:Resilience4j Micrometer 监控 -->
<dependency><groupId>io.github.resilience4j</groupId><artifactId>resilience4j-micrometer</artifactId>
</dependency>

配置熔断规则

配置熔断规则application.yaml

resilience4j:circuitbreaker:instances:deptService:failure-rate-threshold: 50        # 失败率超 50% 熔断minimum-number-of-calls: 5        # 至少调用 5 次才计算wait-duration-in-open-state: 5s   # 熔断后 5 秒尝试恢复sliding-window-size: 10           # 滑动窗口大小sliding-window-type: COUNT_BASED

代码实现

  1. 通过CircuitBreakerFactory 编程式调用
@RestController
public class DeptConsumerController {private final CircuitBreakerFactory circuitBreakerFactory;private final DeptFeignClient deptFeignClient;public DeptConsumerController(CircuitBreakerFactory circuitBreakerFactory,DeptFeignClient deptFeignClient) {this.circuitBreakerFactory = circuitBreakerFactory;this.deptFeignClient = deptFeignClient;}@GetMapping("/consumer/dept/findAll")public List<Dept> findAll() {CircuitBreaker cb = circuitBreakerFactory.create("deptService");return cb.run(() -> deptFeignClient.getDeptList(), // 正常逻辑throwable -> Collections.emptyList() // 降级逻辑);}
}
  1. 使用 @CircuitBreaker注解,推荐
private static final Logger log = LoggerFactory.getLogger(DeptController.class);@GetMapping("/consumer/dept/findAll")
@CircuitBreaker(name = "deptService", fallbackMethod = "fallbackList")
public List<Dept> findAll() {return deptFeignClient.getDeptList();
}// 降级方法(参数需匹配 + 最后一个参数为 Throwable)
public List<Dept> fallbackList(Throwable t) {log.warn("deptService 熔断,返回空列表", t);return Collections.emptyList();
}

Feign集成Resilience4j

  1. 启用 Feign 的 CircuitBreaker 支持
feign:circuitbreaker:enabled: true
  1. @FeignClient 中指定 fallback,触发熔断机制的时候进行服务降级
@FeignClient(name = "springcloud-provider-dept",fallback = DeptFeignFallback.class)
public interface DeptFeignClient {@GetMapping("/dept/list")List<Dept> getDeptList();
}@Component
public class DeptFeignFallback implements DeptFeignClient {@Overridepublic List<Dept> getDeptList() {return Collections.emptyList(); // 降级逻辑}
}

服务降级(Fallback)

定义

服务降级是在服务不可用或熔断时,返回一个兜底的、简化的、可接受的响应,保证系统整体可用性。

目的:

  • 避免用户看到“500错误”或 长时间等待
  • 保证核心功能可用

熔断是触发条件,降级是应对策略

场景

在进行超时、限流、系统过载的事后,都可以使用服务降级;

正常响应

  • 返回数据显示信息;
  • 返回正确内容;
  • 返回支付成功页面;

服务降级后相应

  • 等待中页面
  • 默认显示数据。例如:游客访问权限
  • 空列表,或者缓存数据
  • 响应字段内容:系统繁忙,请稍后重试

实现方式

Feign 降级

前提:

  • 目前的架构是 将API及Service接口拆分开来,服务提供者调用Service,实现Service接口,完成业务数据操作;
  • 服务消费者是使用服务名 通过Eureka注册中心请求调用 服务提供者实现操作;
  • 服务消费者本身没有逻辑实现,只是单纯的转发调用

目前想要尝试的思路是 熔断降级思路,

  • Feign所解决的一大要点是负载均衡,使用FeignClient的时候是在服务提供者实现的Service接口中进行;
  • 目前想要在服务消费者实现,在发生服务熔断的时候,消费方进行降级处理;
  • 如果在FeignClient设置fallback的话 理解上又是对服务提供者做的操作了;
@FeignClient(name = "user-service", fallback = UserFallback.class)
public interface UserClient { ... }@Component
public class UserFallback implements UserClient {public User findById(Long id) {return new User("default", "服务不可用");}
}

@CircuitBreaker降级

@Component
public class DeptFeignFallback implements DeptFeignClient {@Overridepublic List<Dept> getDeptList() {return Collections.emptyList(); // 降级逻辑}
}

Dashboard流监控(不会呀)

定义

Dashboard 是一个可视化监控面板,用于实时查看微服务的:

  • 请求量(QPS)
  • 成功率 / 失败率
  • 熔断状态
  • 响应时间
  • 限流情况

实现方式

启用 Actuator 端点

management:endpoints:web:exposure:include: health,info,metrics,circuitbreakersendpoint:circuitbreakers:enabled: true

集成 Micrometer + Prometheus

  1. 导入依赖
<dependency><groupId>io.micrometer</groupId><artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
  1. 访问http://localhost:8080/actuator/prometheus查看
  2. 根据错误解决问题,只要不是404 Not Found Page 问题不大
  3. 添加prometheusActuator
management:endpoints:web:exposure:include: health,info,metrics,circuitbreakers,prometheusendpoint:circuitbreakers:enabled: true
  1. 测试,有数据正常显示

配置 Prometheus 抓取数据

  1. 下载 Prometheus 解压

地址:https://github.com/prometheus/prometheus/releases/tag/v3.7.2

  1. 配置 Prometheusprometheus.yml
scrape_configs:- job_name: 'spring-boot-app'metrics_path: '/actuator/prometheus'static_configs:- targets: ['localhost:8080']
  1. prometheus.exe启动
  2. 输入resilience4j_circuitbreaker_state测试

使用Grafana可视化

前提条件
  1. Spring Boot 应用(8080)已运行,并暴露了 /actuator/prometheus
  2. Prometheus 已本地安装并成功抓取到指标(访问 http://localhost:9090 能查到 resilience4j_ 开头的指标)
  3. Grafana 已本地安装并启动(访问 http://localhost:3000
使用流程
  1. 下载Grafana,选择OSS开源版本,Windows,安装

下载路径:https://grafana.com/grafana/download/12.2.0?edition=oss&platform=windows

  1. /bin/grafana.exe执行exe,会提示安全风险,添加信任,OK
  2. http://localhost:3000/登录,查看是否能登入,默认账号密码admin/admin
  3. 导入 Resilience4j 官方 Dashboard 模板,导入 Dashboard ID 12657,这12657 是一个控制台的模版显示,

模板地址:https://grafana.com/grafana/dashboards/12657

  1. 导入模版:Dashboards → Import;

  1. 配置数据源:Data Source → Add data source → prometheus;

数据源地址是prometheus的地址localhost:9090;

  1. 选择合适的表盘,edit编辑,在里面设置表盘要显示的内容;

  1. 测试查看

国内的SpringCloud Alibaba

使用Sentinel Dashboard 的集成方案

还有写使用的1.8的内容,SpringBoot2.*时代,所以需要谨慎

SC Alibaba在2023年度 降本增效,好多项目都不维护了

学归学,用归用,不要过于依赖

SC K8s,需要团队中 有 特别牛的架构团队,不然成本太高。

微服务并不一定是最好的,最优的,一定要选择最适合自己的

http://www.dtcms.com/a/535800.html

相关文章:

  • npm 发布node后台安装包和依赖库的方法
  • HarmonyOS语音交互与媒体会话开发实战
  • 【LeetCode】89. 格雷编码
  • 20251027在Ubuntu20.04.6上编译AIO-3576Q38开发板的Buildroot系统解决qt5webengine编译异常的问题
  • 【Linux】文件归属与迁移:chown修改拥有者、chgrp调整所属组,解决团队协作中的权限交接问题
  • 等离激元光催化:从实验室突破到碳中和战场的技术革命
  • 2025年6月全国大学英语四级真题试卷、听力音频及答案解析PDF电子版(三套全)
  • CAS:1628029-06-0,UV-Tracer-炔-琥珀酰亚胺酯,光学特性
  • 中国建设银行网站怎么登录不上去湖北黄石域名注册网站建设
  • 制作网站心得如何建微信公众号平台
  • Redis黑马点评 分布式锁
  • Lua-function的常见表现形式
  • 免费com域名网站提升wordpress性能的插件
  • 面试150——堆
  • shell实战-跳板机和测试主机是否在线
  • 精美课程表软件,课时科目灵活管理
  • MestReNova 16下载安装教程(附安装包)
  • 前端开发中的特殊字符
  • 【超音速专利 CN119515970A】一种适用于电池极片的边缘点距离处理方法、系统及平台
  • CANoe基础讲解04:掌握CANoe Graphics窗口(二)
  • 外国域名注册很多网站制作灯笼的手工做法步骤
  • Spring MVC配置解决跨域请求
  • 从一个nginx镜像启动的容器中分出部分location配置到另外一个nginx容器
  • 探秘仓颉:当函数式编程遇见面向对象王国,当协程风暴席卷并发荒原——从基础语法到实战测试联动的多维编程奇遇记
  • (场景题)怎么实现数据的批量插入?
  • 网站建设与管理案例...建企业网站一般需要多少钱
  • 使用el-table时,某个字段对应多个key值,如何进行展示
  • 空间数据采集与管理(如何使用ArcGIS Pro和Python进行空间数据的管理,确保数据采集和组织的高效性和准确性)
  • WHAT - React Compiler Directives 让手动优化变成过去式
  • API请求关键指标全解:Apipost视角下,从连接到性能的全景分析