← 返回首页
🔍

熔断器

📂 architecture ⏱ 1 min 179 words

熔断器

熔断器原理

熔断器模仿电路断路器,当失败率超过阈值时自动切断调用链路,避免雪崩效应,经过冷却期后尝试恢复。

     ┌─────────┐
     │  Closed  │ ──失败率超阈值──► ┌─────────┐
     └─────────┘                   │  Open    │
          ▲                        └─────────┘
          │                              │
    恢复成功                         冷却期后
          │                              ▼
     ┌─────────┐                   ┌───────────┐
     │  Closed  │ ◄──探测成功──── │ Half-Open │
     └─────────┘                   └───────────┘

Hystrix熔断实现

Hystrix通过线程隔离和熔断器实现服务降级,支持实时监控和配置动态调整。

@HystrixCommand(
    fallbackMethod = "getUserFallback",
    commandProperties = {
        @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
        @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50"),
        @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "5000")
    },
    threadPoolProperties = {
        @HystrixProperty(name = "coreSize", value = "10")
    }
)
public User getUserById(String id) {
    return restTemplate.getForObject("http://user-service/users/" + id, User.class);
}

public User getUserFallback(String id) {
    return new User(id, "默认用户", "服务降级中");
}

Sentinel熔断实现

Sentinel支持滑动窗口统计,提供更精细的熔断策略和实时流量监控。

@SentinelResource(
    value = "getUser",
    fallback = "getUserFallback",
    blockHandler = "getUserBlockHandler"
)
public User getUser(String id) {
    return userService.getUser(id);
}

public User getUserFallback(String id, Throwable e) {
    log.warn("服务降级: {}", e.getMessage());
    return new User(id, "降级用户");
}

public User getUserBlockHandler(String id, BlockException e) {
    return new User(id, "限流用户");
}

熔断器配置

# Sentinel熔断规则
spring:
  cloud:
    sentinel:
      datasource:
        rules:
          - resource: getUser
            grade: 0  # 异常比例
            count: 0.5
            timeWindow: 10
            minRequestAmount: 5
            statIntervalMs: 1000

降级策略

策略 说明 适用场景
快速失败 直接抛出异常 无依赖服务
返回默认值 返回兜底数据 非核心功能
调用本地缓存 返回缓存数据 数据一致性要求低
调用备用服务 切换到备用链路 有冗余服务