
一、前言在微服务架构中流量突增、下游服务超时、报错雪崩是线上最常见的稳定性问题。Sentinel作为阿里开源、经过双11大促打磨的流量防护组件相比 Hystrix 更轻量、功能更强、配置更灵活是目前国内微服务限流、熔断、降级的主流方案。本文带来零残缺、可直接运行、可上线的 Sentinel 完整实战案例包含完整 Maven 依赖全量 YAML 配置限流 熔断双功能代码实现blockHandler / fallback 精准区分面试高频代码硬编码规则 控制台动态规则两种方式OpenFeign 跨服务调用限流熔断识别实战全套线上测试场景 问题总结二、核心核心概念1. 兜底方法区别blockHandlerSentinel 框架拦截异常只处理限流、熔断、系统保护、黑白名单拦截触发的BlockException。fallback捕获业务代码所有异常包含空指针、自定义异常、接口报错等业务异常。2. 核心能力限流QPS 限流、并发线程限流、链路限流、热点参数限流熔断慢调用比例、异常比例、异常数三种熔断策略降级故障自动隔离避免服务雪崩系统防护整机 CPU、负载、QPS 全局保护三、环境与依赖适配版本SpringBoot 2.7.x SpringCloud Alibaba 2021.0.1.0稳定生产版本完整 pom.xml 依赖xmlparentgroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-parent/artifactIdversion2.7.15/versionrelativePath//parentdependencies!-- Spring Web --dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependency!-- Sentinel 流量防护核心依赖 --dependencygroupIdcom.alibaba.cloud/groupIdartifactIdspring-cloud-starter-alibaba-sentinel/artifactIdversion2021.0.1.0/version/dependency!-- Nacos 配置中心用于规则持久化生产必备 --dependencygroupIdcom.alibaba.cloud/groupIdartifactIdspring-cloud-starter-alibaba-nacos-config/artifactIdversion2021.0.1.0/version/dependency!-- OpenFeign 远程调用 --dependencygroupIdorg.springframework.cloud/groupIdartifactIdspring-cloud-starter-openfeign/artifactId/dependency/dependencies四、项目配置文件 application.yml配置控制台地址、开启服务预热初始化适配开发、生产环境yamlserver:port: 8080spring:application:name: sentinel-demo-servicecloud:sentinel:# Sentinel 控制台地址transport:dashboard: 127.0.0.1:8085port: 8719# 关闭懒加载项目启动直接初始化Sentineleager: truenacos:config:server-addr: 127.0.0.1:8848# 开启feign对sentinel的支持feign:sentinel:enabled: true五、启动类javaimport org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.openfeign.EnableFeignClients;SpringBootApplicationEnableFeignClientspublic class SentinelDemoApplication {public static void main(String[] args) {SpringApplication.run(SentinelDemoApplication.class, args);}}六、核心业务代码限流熔断双兜底完整实现统一资源名区分限流熔断兜底、业务异常兜底代码完全解耦符合生产规范。javaimport com.alibaba.csp.sentinel.annotation.SentinelResource;import com.alibaba.csp.sentinel.slots.block.BlockException;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RestController;RestControllerpublic class OrderController {/*** Sentinel 资源名createOrder* blockHandler限流、熔断、系统保护、授权拦截兜底Sentinel 框架异常* fallback业务代码异常兜底代码报错、自定义异常等*/GetMapping(/order/create/{goodsId})SentinelResource(value createOrder,blockHandler blockHandlerCreateOrder,fallback fallbackCreateOrder)public String createOrder(PathVariable Long goodsId) {// 模拟业务异常场景商品999无库存if (goodsId 999) {throw new RuntimeException(商品库存不足下单失败);}// 模拟慢接口用于测试慢调用比例熔断try {Thread.sleep(300);} catch (InterruptedException e) {throw new RuntimeException(e);}return 下单成功商品ID goodsId;}/*** 限流、熔断兜底方法* 规则参数与原方法一致最后追加 BlockException*/public String blockHandlerCreateOrder(Long goodsId, BlockException ex) {// 区分限流、熔断异常返回精准提示if (ex instanceof com.alibaba.csp.sentinel.slots.block.flow.FlowException) {return 【限流兜底】当前下单人数过多请稍后重试;} else if (ex instanceof com.alibaba.csp.sentinel.slots.block.degrade.DegradeException) {return 【熔断兜底】服务暂时繁忙已开启熔断保护请稍后重试;} else {return 【服务防护拦截】请求被限制 ex.getClass().getSimpleName();}}/*** 业务异常兜底方法* 捕获所有业务代码异常*/public String fallbackCreateOrder(Long goodsId, Throwable throwable) {return 【业务异常兜底】商品 goodsId 下单失败 throwable.getMessage();}}七、全局异常处理器生产核心返回429/503标准状态码这是跨服务调用能识别限流/熔断的关键1. 限流异常FlowException→ 返回 HTTP 4292. 熔断异常DegradeException→ 返回 HTTP 503上游 A 服务可通过状态码精准区分「下游限流」还是「下游熔断」javaimport com.alibaba.csp.sentinel.slots.block.BlockException;import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;import com.alibaba.csp.sentinel.slots.block.flow.FlowException;import org.springframework.http.HttpStatus;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.ResponseStatus;import org.springframework.web.bind.annotation.RestControllerAdvice;RestControllerAdvicepublic class SentinelGlobalExceptionHandler {/*** 下游触发限流429 Too Many Requests*/ExceptionHandler(FlowException.class)ResponseStatus(HttpStatus.TOO_MANY_REQUESTS)public String handleFlowException(FlowException e) {return 下游服务触发限流请求过于频繁请稍后重试;}/*** 下游触发熔断503 Service Unavailable*/ExceptionHandler(DegradeException.class)ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)public String handleDegradeException(DegradeException e) {return 下游服务触发熔断服务暂时不可用已开启故障隔离;}/*** 通用Sentinel拦截异常*/ExceptionHandler(BlockException.class)ResponseStatus(HttpStatus.BAD_REQUEST)public String handleBlockException(BlockException e) {return 服务流量拦截 e.getMessage();}}八、OpenFeign 跨服务调用A服务调用B服务精准识别限流/熔断场景说明微服务最经典场景A服务 OpenFeign 调用 B服务B服务接口被 Sentinel 限流/熔断后抛出对应异常经过全局异常处理器返回标准 HTTP 状态码A服务可精准捕获、区分限流/熔断/普通报错做差异化降级策略。1. Feign客户端定义A服务javaimport org.springframework.cloud.openfeign.FeignClient;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;FeignClient(name sentinel-demo-service)public interface BOrderFeignClient {GetMapping(/order/create/{goodsId})String createOrder(PathVariable(goodsId) Long goodsId);}2. A服务调用代码核心区分429限流 / 503熔断javaimport feign.FeignException;import lombok.extern.slf4j.Slf4j;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource;Slf4jRestControllerpublic class AInvokeBController {Resourceprivate BOrderFeignClient bOrderFeignClient;GetMapping(/a/call/b/{goodsId})public String aCallB(PathVariable Long goodsId) {try {// A服务远程调用B服务带Sentinel防护的接口return bOrderFeignClient.createOrder(goodsId);} catch (FeignException e) {// 通过HTTP状态码精准区分下游异常类型int status e.status();if (status 429) {// 下游B服务触发限流log.warn(【跨服务降级】B服务接口限流goodsId:{}, goodsId);return 系统繁忙当前访问人数过多请稍后重试限流降级;} else if (status 503) {// 下游B服务触发熔断log.error(【跨服务熔断】B服务接口熔断服务暂时不可用goodsId:{}, goodsId);return 服务暂时异常已开启熔断保护请稍后重试熔断降级;} else {// 其他业务异常log.error(【远程调用异常】未知错误:{}, e.getMessage());return 服务调用异常请稍后重试;}}}}九、规则配置方式一代码硬编码快速测试无需控制台项目启动自动加载限流、熔断规则适合单元测试、快速验证场景。javaimport 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;Configurationpublic class SentinelRuleConfig {// 与接口资源名保持一致private static final String RESOURCE createOrder;PostConstructpublic void initSentinelRule() {// 1. 限流规则QPS单机阈值2每秒最多2次请求ListFlowRule flowRuleList new ArrayList();FlowRule flowRule new FlowRule();flowRule.setResource(RESOURCE);// 限流维度QPSflowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);// 阈值flowRule.setCount(2);// 流控效果快速失败flowRule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);flowRuleList.add(flowRule);FlowRuleManager.loadRules(flowRuleList);// 2. 熔断规则慢调用比例熔断ListDegradeRule degradeRuleList new ArrayList();DegradeRule degradeRule new DegradeRule();degradeRule.setResource(RESOURCE);// 熔断策略慢调用RTdegradeRule.setGrade(RuleConstant.DEGRADE_GRADE_RT);// 超过250ms判定为慢调用degradeRule.setCount(250);// 慢调用比例超过50%触发熔断degradeRule.setSlowRatioThreshold(0.5);// 最小统计请求数degradeRule.setMinRequestAmount(5);// 熔断窗口期5秒期间直接降级degradeRule.setTimeWindow(5);degradeRuleList.add(degradeRule);DegradeRuleManager.loadRules(degradeRuleList);}}十、规则配置方式二Sentinel 控制台动态配置生产推荐1. 启动控制台下载 sentinel-dashboard-1.8.8.jar执行启动命令shelljava -jar sentinel-dashboard-1.8.8.jar --server.port8085访问地址http://127.0.0.1:8085默认账号密码sentinel / sentinel2. 配置流控规则资源名createOrder阈值类型QPS单机阈值2流控效果快速失败3. 配置熔断降级规则资源名createOrder熔断策略慢调用比例最大RT250ms比例阈值0.5最小请求数5熔断时长5秒十一、完整测试场景含跨服务调用1. 本地接口限流测试快速高频访问http://localhost:8080/order/create/1每秒请求超过2次触发限流返回429提示信息。2. 业务异常 fallback 测试访问http://localhost:8080/order/create/999代码主动抛出业务异常触发 fallback 兜底。3. 跨服务限流识别测试A调B高频访问http://localhost:8080/a/call/b/1B服务触发限流后返回429A服务捕获状态码执行限流专属降级逻辑。4. 跨服务熔断识别测试A调B批量并发请求接口触发B服务慢调用熔断B返回503A服务捕获后执行熔断专属降级逻辑不再重试。十二、生产核心规范与避坑总结1. 方法签名硬性规则blockHandler 方法参数必须和原方法一致末尾必须追加BlockExceptionfallback 方法参数同原方法可追加Throwable捕获所有异常2. 跨服务调用核心规范重点限流429服务正常、流量打满可短时重试、排队、友好提示熔断503服务异常隔离禁止重试直接走本地兜底/缓存禁止统一返回200状态码业务码会导致上游无法精准区分故障类型丢失降级策略Feign 底层逻辑只要 HTTP 状态码 不是 200~299不会把 body 正常返回直接抛出 FeignExceptionFeignException 内部会保存原始 HTTP 状态码通过 e.status() 获取。3. 生产建议禁止使用代码硬编码规则务必使用Nacos 持久化规则支持动态修改、集群统一生效核心接口配置限流熔断双重防护非核心接口可只配置限流统一 429/503 状态码规范统一上下游降级逻辑开启 Sentinel 监控日志线上快速定位流量、熔断异常十三、总结本文实现了零缺失、可直接投产的 Sentinel 限流熔断完整案例覆盖本地接口防护 OpenFeign跨服务调用、上下游异常识别、差异化降级全场景厘清了blockHandler、fallback、限流熔断跨服务传递的核心原理。Sentinel 凭借轻量、高可用、功能丰富的特性完全可以替代 Hystrix作为微服务稳定性防护的核心组件是中高级开发必备的技术栈。