Spring Cloud 熔断降级详解:Sentinel 实战与保险丝类比
分布式系统中的熔断降级机制,通过保险丝类比帮助理解。介绍了 Sentinel 核心概念、配置及实战步骤,涵盖注解方式、OpenFeign 集成、规则持久化(Nacos)及全局异常处理。提供了最佳实践建议,包括阈值设置、降级策略和监控告警,旨在提升微服务架构的稳定性。

分布式系统中的熔断降级机制,通过保险丝类比帮助理解。介绍了 Sentinel 核心概念、配置及实战步骤,涵盖注解方式、OpenFeign 集成、规则持久化(Nacos)及全局异常处理。提供了最佳实践建议,包括阈值设置、降级策略和监控告警,旨在提升微服务架构的稳定性。

熔断降级 是分布式系统中保护服务稳定性的重要机制。当某个服务出现故障或响应时间过长时,系统会自动切断对该服务的调用,避免故障蔓延,防止雪崩效应。
在微服务架构中,服务之间相互依赖:
用户请求 → 服务 A → 服务 B → 服务 C
如果服务 C 出现故障:
┌─────────────────────────────────────────────┐
│ 家庭电路保险丝 │
├─────────────────────────────────────────────┤
│ │
│ 正常情况: │
│ 电流 ───────→ 保险丝 ───────→ 电器正常工作 │
│ (导通) │
│ │
│ 异常情况(短路/过载): │
│ 电流过大 ─────→ 保险丝熔断 ─────→ 电路断开 │
│ (保护) │
│ │
│ 恢复后: │
│ 更换保险丝 ─────→ 电路恢复正常 │
│ │
└─────────────────────────────────────────────┘
| 保险丝 | 熔断器 |
|---|---|
| 电流过大时熔断 | 异常率达到阈值时熔断 |
| 断开后电路不通 | 熔断后直接返回降级结果 |
| 冷却后可恢复 | 半开后尝试恢复 |
| 保护电路安全 | 保护服务稳定性 |
Sentinel 是阿里巴巴开源的一套流量控制、熔断降级组件,主要用于:
| 概念 | 说明 | 示例 |
|---|---|---|
| 资源 | 任何需要保护的逻辑 | 接口、方法、代码块 |
| 规则 | 流控、熔断的策略 | QPS>100 限流,失败率>50% 熔断 |
| 指标 | 统计数据 | QPS、RT、失败率 |
| 策略 | 处理方式 | 直接拒绝、Warm Up、匀速排队 |
| 特性 | Sentinel | Hystrix |
|---|---|---|
| 熔断策略 | 失败率、异常数、响应时间 | 失败率 |
| 流量控制 | ✅ 支持 | ❌ 不支持 |
| 实时监控 | ✅ 控制台实时监控 | ❌ 需要额外工具 |
| 性能 | 高性能 | 较低 |
| 扩展性 | SPI 扩展 | 扩展性一般 |
| 维护状态 | 活跃维护 | 已停止维护 |
<!-- Spring Cloud Alibaba -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2022.0.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- Sentinel 核心依赖 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!-- Sentinel 数据源-Nacos(持久化规则) -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
<!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
server:
port: 8080
spring:
application:
name: order-service
cloud:
sentinel:
enabled: true
transport:
dashboard: localhost:8080
port: 8719
heartbeat-interval-ms: 5000
web-context-unify: false
block-handler: com.example.handler.BlockExceptionHandler
fallback: com.example.handler.FallbackExceptionHandler
management:
endpoints:
web:
exposure:
include: '*'
@SpringBootApplication
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
}
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.stereotype.Service;
@Service
public class OrderService {
/**
* 创建订单接口
* @SentinelResource 注解说明:
* - value: 资源名称,唯一标识
* - blockHandler: 限流/熔断时的处理方法
* - fallback: 降级时的处理方法
*/
@SentinelResource(
value = "createOrder",
blockHandler = "handleBlock",
fallback = "handleFallback"
)
public String createOrder(String productId, Integer count) {
// 模拟业务逻辑
System.out.println("创建订单:商品 ID=" + productId + ", 数量=" + count);
// 模拟异常情况(用于测试降级)
if ("error".equals(productId)) {
throw new RuntimeException("商品不存在");
}
return "订单创建成功!";
}
/**
* 限流/熔断处理方法
* 注意:方法签名必须与原方法一致,最后添加 BlockException 参数
*/
public String handleBlock(String productId, Integer count, BlockException ex) {
return "系统繁忙,请稍后再试(限流/熔断)";
}
/**
* 降级处理方法
* 注意:方法签名必须与原方法一致,最后可添加 Throwable 参数
*/
public String handleFallback(String productId, Integer count, Throwable ex) {
return "服务暂时不可用,已启动降级处理";
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private OrderService orderService;
@PostMapping("/create")
public String createOrder(@RequestParam String productId, @RequestParam Integer count) {
return orderService.createOrder(productId, count);
}
/**
* 测试接口:模拟慢调用(用于测试 RT 熔断)
*/
@GetMapping("/slow")
@SentinelResource(value = "slowApi", blockHandler = "handleBlock")
public String slowApi() throws InterruptedException {
Thread.sleep(1000); // 模拟慢调用
return "正常响应";
}
public String handleBlock(BlockException ex) {
return "接口响应太慢,已触发熔断";
}
}
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class SentinelRuleConfig {
@PostConstruct
public void initRules() {
initFlowRules();
initDegradeRules();
}
/**
* 流量控制规则
*/
private void initFlowRules() {
List<FlowRule> rules = new ArrayList<>();
// 规则 1:创建订单接口限流
FlowRule rule1 = new FlowRule();
rule1.setResource("createOrder");
rule1.setGrade(RuleConstant.FLOW_GRADE_QPS); // QPS 限流
rule1.setCount(10); // 每秒最多 10 个请求
rule1.setStrategy(RuleConstant.STRATEGY_DIRECT); // 直接拒绝
rule1.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT); // 快速失败
rules.add(rule1);
// 规则 2:慢查询 API 限流
FlowRule rule2 = new FlowRule();
rule2.setResource("slowApi");
rule2.setGrade(RuleConstant.FLOW_GRADE_QPS);
rule2.setCount(2); // 每秒最多 2 个请求
rule2.setStrategy(RuleConstant.STRATEGY_DIRECT);
rules.add(rule2);
FlowRuleManager.loadRules(rules);
}
/**
* 熔断降级规则
*/
private void initDegradeRules() {
List<DegradeRule> rules = new ArrayList<>();
// 规则 1:慢调用比例熔断
DegradeRule rule1 = new DegradeRule();
rule1.setResource("slowApi");
rule1.setGrade(RuleConstant.DEGRADE_GRADE_RT); // 慢调用比例
rule1.setCount(500); // 响应时间超过 500ms 视为慢调用
rule1.setTimeWindow(10); // 熔断时长 10 秒
rule1.setMinRequestAmount(5); // 最小请求数
rule1.setSlowRatioThreshold(0.5); // 慢调用比例阈值 50%
rules.add(rule1);
// 规则 2:异常比例熔断
DegradeRule rule2 = new DegradeRule();
rule2.setResource("createOrder");
rule2.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO); // 异常比例
rule2.setCount(0.5); // 异常比例 50%
rule2.setTimeWindow(10); // 熔断时长 10 秒
rule2.setMinRequestAmount(5); // 最小请求数
rules.add(rule2);
// 规则 3:异常数熔断
DegradeRule rule3 = new DegradeRule();
rule3.setResource("createOrder");
rule3.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT); // 异常数
rule3.setCount(10); // 异常数超过 10 个
rule3.setTimeWindow(10); // 熔断时长 10 秒
rule3.setMinRequestAmount(5);
rules.add(rule3);
DegradeRuleManager.loadRules(rules);
}
}
# application.yml
feign:
sentinel:
enabled: true # 开启 Feign 对 Sentinel 的支持
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* 库存服务 Feign 客户端
* fallback: 指定降级处理类
*/
@FeignClient(
name = "inventory-service",
path = "/inventory",
fallback = InventoryServiceFallback.class
)
public interface InventoryServiceClient {
@GetMapping("/deduct")
String deductStock(@RequestParam("productId") String productId, @RequestParam("count") Integer count);
}
import org.springframework.stereotype.Component;
@Component
public class InventoryServiceFallback implements InventoryServiceClient {
@Override
public String deductStock(String productId, Integer count) {
// 降级逻辑:返回默认值或缓存数据
return "库存服务暂时不可用,已为您预留库存,稍后将自动扣减";
}
}
spring:
cloud:
sentinel:
datasource:
flow:
nacos:
server-addr: localhost:8848
data-id: ${spring.application.name}-flow-rules
group-id: SENTINEL_GROUP
rule-type: flow
data-type: json
degrade:
nacos:
server-addr: localhost:8848
data-id: ${spring.application.name}-degrade-rules
group-id: SENTINEL_GROUP
rule-type: degrade
data-type: json
流控规则 (order-service-flow-rules.json)
[{"resource":"createOrder","limitApp":"default","grade":1,"count":10,"strategy":0,"controlBehavior":0,"clusterMode":false}]
熔断规则 (order-service-degrade-rules.json)
[{"resource":"slowApi","grade":0,"count":500,"timeWindow":10,"minRequestAmount":5,"slowRatioThreshold":0.5,"statIntervalMs":1000}]
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.HashMap;
import java.util.Map;
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* 统一处理 Sentinel 异常
*/
@ExceptionHandler(BlockException.class)
public Map<String, Object> handleBlockException(BlockException ex) {
Map<String, Object> result = new HashMap<>();
result.put("code", 429);
result.put("message", "服务限流或熔断,请稍后重试");
// 区分不同类型的异常
if (ex instanceof FlowException) {
result.put("type", "限流");
} else if (ex instanceof DegradeException) {
result.put("type", "熔断降级");
} else if (ex instanceof ParamFlowException) {
result.put("type", "热点参数限流");
} else if (ex instanceof AuthorityException) {
result.put("type", "授权规则不通过");
}
return result;
}
}
# 1. 测试流控规则
# 使用 Apache Bench 进行压测
ab -n 100 -c 20 http://localhost:8080/order/create?productId=123&count=1
# 2. 测试慢调用熔断
# 访问慢接口多次
for i in {1..10}; do curl http://localhost:8080/order/slow; done
# 3. 测试异常熔断
# 调用会抛出异常的接口
curl http://localhost:8080/order/create?productId=error&count=1
访问 http://localhost:8080 可以看到:
| 场景 | 慢调用 RT 阈值 | 异常比例阈值 | 熔断时长 |
|---|---|---|---|
| 核心接口 | 1000ms | 30% | 5-10 秒 |
| 普通接口 | 2000ms | 50% | 10-30 秒 |
| 非核心接口 | 3000ms | 70% | 30-60 秒 |
/**
* 降级策略优先级:
* 1. 返回缓存数据(最新缓存或默认值)
* 2. 返回友好提示
* 3. 调用备用服务
*/
public String degradeStrategy() {
// 优先级 1:返回缓存
String cached = cache.get(key);
if (cached != null) {
return cached;
}
// 优先级 2:返回默认值
return "服务繁忙,请稍后重试";
}
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class SentinelMonitor {
@Scheduled(cron = "0/5 * * * * ?")
public void monitorMetrics() {
// 监控熔断状态
List<DegradeRule> rules = DegradeRuleManager.getRules();
for (DegradeRule rule : rules) {
// 获取资源状态
ResourceNode resourceNode = ClusterBuilderSlot.getClusterNode(rule.getResource());
if (resourceNode != null) {
double passQps = resourceNode.passQps();
double blockQps = resourceNode.blockQps();
double exception = resourceNode.totalException();
// 发送告警
if (blockQps > 0 || exception > 0) {
alertService.sendAlert("服务异常:资源=" + rule.getResource());
}
}
}
}
}
熔断降级是微服务架构中保护系统稳定性的重要机制:
✅ 核心价值:
✅ 关键要点:
✅ 实战建议:
通过合理使用 Sentinel,可以有效提升微服务架构的稳定性和可靠性!

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
查找任何按下的键的javascript键代码、代码、位置和修饰符。 在线工具,Keycode 信息在线工具,online
JavaScript 字符串转义/反转义;Java 风格 \uXXXX(Native2Ascii)编码与解码。 在线工具,Escape 与 Native 编解码在线工具,online
使用 Prettier 在浏览器内格式化 JavaScript 或 HTML 片段。 在线工具,JavaScript / HTML 格式化在线工具,online
Terser 压缩、变量名混淆,或 javascript-obfuscator 高强度混淆(体积会增大)。 在线工具,JavaScript 压缩与混淆在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online