Hystrix
Hystrix 是 Netflix 开源的服务容错组件,用于防止分布式系统中的雪崩效应(一个服务故障导致整个链路瘫痪)。提供降级(服务不可用时返回兜底结果)、熔断(故障率过高时切断请求)、线程隔离、请求缓存等功能。
适用场景:微服务架构的服务容错、需要防止雪崩效应的场景。
⚠️ 注意:Hystrix 已进入维护状态,新项目推荐使用 Sentinel。
提示
Netflix服务容错组件,提供降级、熔断、线程隔离和实时监控
核心功能
| 功能 | 说明 |
|---|---|
| 服务降级 | 调用失败时返回兜底数据(如"服务器繁忙,请稍后重试") |
| 服务熔断 | 故障率过高时短路请求(直接返回降级结果,不再调用下游) |
| 线程隔离 | 限制调用方并发,避免资源耗尽(每个服务独立线程池) |
| 实时监控 | Hystrix Dashboard 监控熔断器状态 |
降级使用
引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>定义降级方法
启动类添加 @Enable<mark>Hystrix</mark>,方法上使用 @HystrixCommand:
@HystrixCommand(fallbackMethod = "fallback")
@GetMapping("/test")
public Result test() {
return remoteClient.test();
}
public Result fallback() {
return Result.failure("服务器繁忙,请稍后重试");
}超时降级
ribbon.ReadTimeout=5000
hystrix.command.default.execution.timeout.enabled=true
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=5000熔断机制
熔断状态
| 状态 | 说明 |
|---|---|
| Closed | 熔断关闭,请求正常通过 |
| Open | 熔断开启,快速失败返回降级(不再调用下游服务) |
| Half-Open | 半熔断,尝试恢复服务(放行少量请求探测下游是否恢复) |
配置参数
| 参数 | 说明 | 默认值 |
|---|---|---|
| circuitBreaker.requestVolumeThreshold | 熔断触发最小请求数 | 20 |
| circuitBreaker.sleepWindowInMilliseconds | 熔断持续时间 | 5000ms |
| circuitBreaker.errorThresholdPercentage | 错误率阈值 | 50% |
代码示例
@HystrixCommand(fallbackMethod = "fallback", commandProperties = {
@HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
@HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "1000"),
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"),
})
public String circuitBreaker(Integer id) {
if (id < 0) throw new RuntimeException("id 不能是负数");
return "OK";
}线程隔离
@HystrixCommand(fallbackMethod = "fallback",
threadPoolKey = "goods",
threadPoolProperties = {
@HystrixProperty(name = "coreSize", value = "2"),
@HystrixProperty(name = "maxQueueSize", value = "1")
})
public Result test() {
return remoteClient.test();
}服务监控
引入依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>暴露端点:management.endpoints.web.exposure.include=hystrix.stream
常见问题处理
降级不生效
- 检查
@HystrixCommand注解是否正确 - 确认
@EnableHystrix注解是否添加 - 检查 fallback 方法签名是否匹配
误熔断
- 调整熔断阈值:
circuitBreaker.errorThresholdPercentage - 增加熔断时长:
circuitBreaker.sleepWindowInMilliseconds - 检查下游服务响应时间