【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)
定义
服务熔断 是一种自动保护机制:当某个服务调用失败率过高时,系统会“熔断”该链路,快速失败,避免请求堆积而导致雪崩
熔断的三种状态:
- Closed(闭合):正常调用,记录成功/失败次数;
- Open(打开):拒绝请求,不调用任何服务,快速返回错误或降级;
- 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
代码实现
- 通过
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() // 降级逻辑);}
}
- 使用
@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
- 启用 Feign 的 CircuitBreaker 支持
feign:circuitbreaker:enabled: true
- 在
@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
- 导入依赖
<dependency><groupId>io.micrometer</groupId><artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
- 访问
http://localhost:8080/actuator/prometheus查看 - 根据错误解决问题,只要不是404 Not Found Page 问题不大
- 添加
prometheus在Actuator中
management:endpoints:web:exposure:include: health,info,metrics,circuitbreakers,prometheusendpoint:circuitbreakers:enabled: true
- 测试,有数据正常显示

配置 Prometheus 抓取数据
- 下载
Prometheus解压
地址:https://github.com/prometheus/prometheus/releases/tag/v3.7.2
- 配置
Prometheus,prometheus.yml
scrape_configs:- job_name: 'spring-boot-app'metrics_path: '/actuator/prometheus'static_configs:- targets: ['localhost:8080']
prometheus.exe启动- 输入
resilience4j_circuitbreaker_state测试


使用Grafana可视化
前提条件
- Spring Boot 应用(8080)已运行,并暴露了
/actuator/prometheus- Prometheus 已本地安装并成功抓取到指标(访问
http://localhost:9090能查到resilience4j_开头的指标)- Grafana 已本地安装并启动(访问
http://localhost:3000)
使用流程
- 下载
Grafana,选择OSS开源版本,Windows,安装
下载路径:https://grafana.com/grafana/download/12.2.0?edition=oss&platform=windows
/bin/grafana.exe执行exe,会提示安全风险,添加信任,OKhttp://localhost:3000/登录,查看是否能登入,默认账号密码admin/admin- 导入 Resilience4j 官方 Dashboard 模板,导入
Dashboard ID 12657,这12657 是一个控制台的模版显示,
模板地址:https://grafana.com/grafana/dashboards/12657
- 导入模版:Dashboards → Import;

- 配置数据源:Data Source → Add data source → prometheus;
数据源地址是prometheus的地址localhost:9090;

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

- 测试查看

国内的SpringCloud Alibaba
使用Sentinel Dashboard 的集成方案
还有写使用的1.8的内容,SpringBoot2.*时代,所以需要谨慎
SC Alibaba在2023年度 降本增效,好多项目都不维护了
学归学,用归用,不要过于依赖
