
Spring Boot 项目里怎么加 Sentinel 依赖不踩包冲突
Sentinel 和 Spring Cloud Alibaba 版本强绑定,直接写最新版 sentinel-spring-cloud-gateway-filter 或乱选 spring-cloud-starter-alibaba-sentinel 很容易和已有的 spring-boot-starter-webflux、spring-cloud-gateway 冲突,表现是启动报 NoClassDefFoundError: com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler 或限流完全不生效。
实操建议:
立即学习“Java免费学习笔记(深入)”;
- 用官方推荐的版本对齐表:Spring Boot 2.7.x → Spring Cloud 2021.0.x → Spring Cloud Alibaba 2021.0.5.0;Spring Boot 3.2.x → Spring Cloud 2023.0.x → Spring Cloud Alibaba 2023.0.0.0
- 只引入一个 starter:
spring-cloud-starter-alibaba-sentinel(WebMvc 场景)或spring-cloud-starter-alibaba-sentinel-gateway(网关场景),别两个一起引 - 排除掉旧版
sentinel-transport-simple-http:它会干扰控制台连接,尤其在 JDK 17+ 下抛ClassNotFoundException: sun.misc.BASE64Encoder
application.yml 里哪些配置项必须设,哪些可以删
很多人抄配置时把官网示例全粘过来,结果 sentinel.eager 没开导致第一次请求才初始化上下文,sentinel.transport.dashboard 写错端口连不上控制台,或者漏了 sentinel.filter.order 导致 Filter 被其他 Filter 挡住。
实操建议:
立即学习“Java免费学习笔记(深入)”;
- 必填项只有三个:
sentinel.transport.dashboard(如localhost:8080)、sentinel.transport.port(客户端通信端口,默认 8719,别被防火墙拦)、sentinel.eager设为true(避免首次调用延迟) -
sentinel.filter.url-patterns可删——默认拦截所有/**,除非你明确要排除健康检查路径 -
sentinel.datasource.nacos这类动态规则源配置,没接 Nacos 就别写,否则启动直接报DataSourceNotFoundException
为什么 @SentinelResource 注解加了但限流不触发
常见现象:方法上写了 @SentinelResource(value = "getUser", blockHandler = "handleBlock"),控制台也看到资源名,但压测时完全不限流。根本原因是没走 Sentinel 的资源埋点入口——比如用了 FeignClient、@Async、或者方法被 AOP 代理多次,导致实际执行的不是原方法。
实操建议:
立即学习“Java免费学习笔记(深入)”;
- 确认该方法是否被 Spring 管理:非
@Service/@Component类里的方法,@SentinelResource无效 - 禁用 CGLIB 代理干扰:在启动类加
@EnableAspectJAutoProxy(exposeProxy = true),并在方法内用AopContext.currentProxy()调用自身(仅限不得已场景) - 更稳的方式是手动定义资源:在方法里用
SphU.entry("getUser")+try-catch BlockException,绕过注解解析逻辑
控制台连上了,但实时监控为空或 QPS 始终为 0
这通常不是代码问题,而是流量没进 Sentinel 的统计链路。典型原因包括:应用没启用 WebMvc 自动配置、用了 Undertow 容器但没配适配器、或者 Controller 方法返回了 ResponseEntity 但没设正确 MediaType,导致 Sentinel 的 WebMvcFilter 捕获不到响应状态。
实操建议:
立即学习“Java免费学习笔记(深入)”;
- 检查
/actuator/sentinel端点是否返回正常 JSON,如果 404,说明sentinel-web-servlet模块没加载成功 - 用 Undertow?必须显式添加
sentinel-undertow-adapter依赖,并在配置类中注册UndertowWebServerFactoryCustomizer - 确认 Controller 方法返回类型是
String、Map或带@ResponseBody的 POJO,别用原始HttpServletResponse写响应体
最常被忽略的一点:Sentinel 控制台默认每 10 秒拉一次客户端心跳,但如果你本地开发时反复重启应用,旧的客户端实例还在控制台挂着,新实例的监控数据会被“挤掉”——得手动在控制台点击“刷新机器列表”或清空浏览器缓存再重进。











