目录
一、nacos-consumer pom.xml 新增 Sentinel 依赖
二、application.yml(nacos-consumer)核心配置
三、降级兜底类 HelloFeignFallback(重点!)(实现HelloFeign接口)
四、Feign 接口改造 HelloFeign(增加 fallback)
五、下载 sentinel-dashboard-1.8.10.jar
接上篇:
eclipse中搭建Spring Boot4 + SCA 2025.1.0.0 + Nacos + OpenFeign 完整 Demo-优快云博客
一、nacos-consumer pom.xml 新增 Sentinel 依赖
<!-- sentinel starter -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
二、application.yml(nacos-consumer)核心配置
server:
port: 8082
spring:
application:
name: nacos-consumer
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
username: nacos
password: 111111
#分组名
group: test
sentinel:
transport:
dashboard: 127.0.0.1:8079 # sentinel控制台地址
port: 8719 # 客户端和控制台通信端口,默认即可
feign:
sentinel:
enabled: true # ✅ 关键开关,开启Feign对Sentinel支持,不打开降级不生效
三、降级兜底类 HelloFeignFallback(重点!)(实现HelloFeign接口)
HelloFeignFallback.java
package com.demo.consumer;
import org.springframework.stereotype.Component;
@Component
public class HelloFeignFallback implements HelloFeign{
@Override
public String hello(String name) {
// 降级逻辑:provider宕机、超时、sentinel熔断限流都会走到这里
return "【Sentinel降级兜底】provider服务暂时不可用,请稍后重试!入参:" + name;
}
}
要点:
- 必须
@Component交给 Spring 管理 - 方法签名和 Feign 接口完全一致
- 降级里面不要查库、不要远程调用,尽量返回静态兜底,防止雪崩
四、Feign 接口改造 HelloFeign(增加 fallback)
HelloFeign.java (fallback = HelloFeignFallback.class)
package com.demo.consumer;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
// name 和提供者 spring.application.name 保持一致
@FeignClient(name = "nacos-provider", fallback = HelloFeignFallback.class)
public interface HelloFeign {
@GetMapping("/hello/{name}")
String hello(@PathVariable("name") String name);
}
五、下载 sentinel-dashboard-1.8.10.jar
https://download.youkuaiyun.com/download/Bof_jangle/93817612
java -Dserver.port=8079 -jar sentinel-dashboard-1.8.10.jar
访问http://127.0.0.1:8079 账号密码:sentinel / sentinel
六、测试步骤
- 启动 Nacos → provider-app → consumer-app
- 访问:
http://127.0.0.1:8082/call/jangle正常返回 provider 的结果
- 停掉 provider-app,再次访问接口 → 直接返回兜底文字,降级生效 ✅

- 打开 Sentinel 控制台,簇点链路里能看到 Feign 资源:GET:http://nacos-provider/hello/{name}
- 给这个资源配置 熔断规则 / 限流规则:
- 熔断:慢调用比例、异常比例、异常数
- 限流:QPS 阈值
七、高频坑点
feign.sentinel.enabled=true忘记配置 → fallback 完全不触发- Fallback 类没加
@Component→ 报错找不到 bean @PathVariable不写参数名 → 遇到的-parameters报错- Sentinel 控制台看不到链路:第一次访问接口之后才会注册资源
注:
- 熔断(circuit break):停止调用下游,保护系统,是动作
- 降级(fallback):熔断之后,返回兜底内容的方案,是熔断之后的处理手段
- 限流:请求太多了,新来的请求不让进来(挡外面)
一句话:熔断是 “不访问下游”,降级是 “给个兜底返回”
本文详解Spring Cloud Alibaba中Sentinel的熔断、降级与限流三大核心能力,涵盖依赖引入、YAML配置、Feign接口fallback实现、兜底类编写规范、Sentinel Dashboard部署及规则配置,并强调熔断(停止调用下游)、降级(返回静态兜底)和限流(QPS控制)的技术差异与高频避坑要点。
490

被折叠的 条评论
为什么被折叠?



