Spring Cloud Alibaba Sentinel:Boot 3 接入、规则持久化与故障边界
基线:Spring Boot 3、Spring Cloud 202x.x、Spring Cloud Alibaba 对应 BOM、Sentinel 1.8.x 和 Nacos 2.x。版本必须按官方兼容矩阵组合。
1. Sentinel 解决什么
Sentinel 对资源进行流量控制、熔断降级、系统保护和热点参数限流。它解决的是服务过载和故障传播,不是数据一致性、消息可靠性或业务重试。
典型调用链:
HTTP / RPC / 方法调用
-> Sentinel 资源入口
-> Slot 链
-> 规则检查
-> 放行或 BlockException
2. Spring Boot 3 接入
使用 Spring Cloud Alibaba BOM 管理依赖,不要单独拼装 starter 版本。Boot 3 使用 Jakarta 命名空间,旧版 Boot 2 依赖不能混用。
spring:
application:
name: order-service
cloud:
sentinel:
enabled: true
eager: false
transport:
dashboard: <SENTINEL_DASHBOARD_HOST>:8719
port: 8719
实际属性名以当前 starter 的配置元数据为准。Dashboard 端口和客户端心跳端口都应放在内网或受保护网络中。
3. 保护业务资源
@SentinelResource(
value = "order.create",
blockHandler = "blocked",
fallback = "fallback")
public Order create(CreateOrderCommand command) {
return service.create(command);
}
public Order blocked(CreateOrderCommand command, BlockException ex) {
throw new TooManyRequestsException();
}
public Order fallback(CreateOrderCommand command, Throwable ex) {
throw new ServiceUnavailableException(ex);
}
blockHandler 处理 Sentinel 限流或降级异常;fallback 处理业务执行异常。不要把所有异常都转换成“限流”,否则会掩盖真实故障。
4. 规则持久化
仅在 Dashboard 内存中创建规则,客户端重启后可能丢失。生产环境使用 Nacos 等外部数据源持久化流控、降级、热点和系统规则,并明确配置 namespace、group、dataId、鉴权和回滚策略。
规则变更需要审计、灰度和版本控制。Dashboard 本身不是完整的生产配置治理系统。
5. Web 与 Feign 适配
Spring MVC、WebFlux、RestTemplate 和 Feign 的资源命名和拦截器由对应适配模块负责。启用适配后应验证:
- URL 是否被规范化,避免每个 ID 产生独立资源;
- HTTP 方法是否纳入资源名;
- BlockException 是否返回正确状态码;
- Feign 重试与 Sentinel fallback 是否重复执行副作用。
6. 生产边界
固定所有依赖和镜像版本;保护 Dashboard 和 Actuator;限制规则变更权限;监控阻塞数、拒绝数、异常率、RT、线程池和下游连接池。Sentinel 不能替代超时、连接池上限、幂等和业务级降级。
源码阅读时以实际依赖版本为准。自动配置入口可能从 spring.factories 迁移到 AutoConfiguration.imports,类名和初始化顺序不应跨版本直接照抄。