在 Spring Boot 中使用 Sentinel 非常方便,Spring Cloud Alibaba 提供了 spring-cloud-starter-alibaba-sentinel
组件,可以快速将 Sentinel 集成到你的 Spring Boot 应用中,并利用其强大的流量控制和容错能力。
下面是一个详细的步骤指南
步骤 1: 添加 Sentinel 依赖
首先,需要在你的 pom.xml
文件中添加 Spring Cloud Alibaba Sentinel 的依赖。确保你已经配置了 Spring Cloud Alibaba 的依赖管理 (spring-cloud-alibaba-dependencies
)。
<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
如果你需要使用 Sentinel 的持久化功能,例如将规则持久化到 Nacos 配置中心,还需要添加相应的依赖,例如:
<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<dependency><groupId>com.alibaba.csp</groupId><artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
步骤 2: 配置 Sentinel
在 application.properties
或 application.yml
文件中配置 Sentinel 的基本信息。 至少需要配置 Sentinel 控制台的地址,以便你可以通过控制台查看监控数据和管理规则。
spring:application:name: your-spring-boot-app # 应用名称,Sentinel 控制台中会显示cloud:sentinel:transport:dashboard: localhost:8080 # Sentinel 控制台的地址 (默认端口 8080)port: 8719 # Sentinel 客户端与控制台通信的端口,默认 8719,可以自定义,避免冲突# 如果需要持久化规则到 Nacos,还需要配置 Nacos 相关信息
# nacos:
# config:
# server-addr: your-nacos-server-address:8848
注意: 你需要先启动 Sentinel 控制台,才能在控制台中看到你的 Spring Boot 应用的监控数据和配置规则。 你可以从 Sentinel 的 GitHub 仓库下载 Sentinel 控制台的 JAR 包并启动。
步骤 3: 定义受保护的资源
在 Spring Boot 中,你可以使用以下方式来定义需要 Sentinel 保护的资源:
方式一:使用 @SentinelResource
注解
这是最常用的方式,通过在方法上添加 @SentinelResource
注解,可以声明该方法为一个受保护的资源。
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.stereotype.Service;@Service
public class MyService {@SentinelResource(value = "myResource", blockHandler = "handleBlock")public String doSomething() {// 业务逻辑return "Success";}// BlockHandler 方法,用于处理 BlockException,即限流、熔断等 block 情况public String handleBlock(BlockException e) {return "Blocked by Sentinel: " + e.getClass().getSimpleName(); // 返回被 Sentinel 拦截的提示信息}
}
@SentinelResource(value = "myResource")
:value
属性指定资源的名称,在 Sentinel 控制台中会显示这个名称。blockHandler = "handleBlock"
:blockHandler
属性指定了当资源被限流、熔断等 block 时,应该调用的 blockHandler 方法。handleBlock
方法的签名需要和被保护的方法一致,但最后一个参数必须是BlockException
类型。blockHandler
方法负责处理 block 逻辑,例如返回友好的提示信息或执行降级操作。
方式二:编程式 API 定义资源
除了注解,你也可以使用 Sentinel 提供的编程式 API 来定义资源,这种方式更加灵活,可以更细粒度地控制资源的入口和出口。
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.stereotype.Service;@Service
public class MyService {public String doSomethingProgrammatically() {Entry entry = null;try {entry = SphU.entry("myProgrammaticResource"); // 定义资源名// 被保护的业务逻辑return "Success from Programmatic Resource";} catch (BlockException e) {// 处理 BlockException,例如限流、熔断等return "Blocked by Sentinel (Programmatic): " + e.getClass().getSimpleName();} catch (Exception ex) {// 业务逻辑异常,需要记录到 Sentinel 的异常统计中Tracer.traceEntry(entry, ex);throw ex;} finally {if (entry != null) {entry.exit(); // 保证 exit() 被调用,否则会导致统计数据不准确}}}
}
SphU.entry("myProgrammaticResource")
:SphU.entry()
方法用于定义一个资源入口,参数为资源名称。 它会返回一个Entry
对象,用于标记资源的入口。entry.exit()
: 在finally
块中调用entry.exit()
,表示资源调用结束。 必须确保entry.exit()
被调用,否则会导致 Sentinel 的统计数据不准确。BlockException
捕获: 需要捕获BlockException
异常,并处理限流、熔断等 block 情况。Tracer.traceEntry(entry, ex)
: 如果业务逻辑发生异常,需要使用Tracer.traceEntry()
方法将异常信息记录到 Sentinel 的异常统计中。
步骤 4: 配置流控规则
定义了受保护的资源后,你需要配置流控规则,告诉 Sentinel 如何对这些资源进行保护。 你可以通过以下方式配置规则:
方式一:在 Sentinel 控制台配置
这是最推荐的方式,通过 Sentinel 控制台,你可以可视化地配置和管理规则,实时生效,无需重启应用。
- 访问 Sentinel 控制台: 访问你在
application.properties
中配置的spring.cloud.sentinel.transport.dashboard
地址(默认http://localhost:8080
)。 - 找到你的应用: 在控制台的 “簇点链路” 或 “机器列表” 中找到你的 Spring Boot 应用。
- 配置规则: 在 “流控规则”、“降级规则”、“热点规则” 等菜单中,为你的资源配置相应的规则。 例如,为 “myResource” 配置一个 QPS 为 2 的流控规则。
- 按如下操作
添加“流控”规则
添加“熔断”机制
方式二:在代码中编程式配置规则
你也可以在代码中编程式地配置规则,这种方式更适合自动化配置或单元测试。
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;import java.util.ArrayList;
import java.util.List;@Component
public class FlowRuleConfig implements CommandLineRunner {@Overridepublic void run(String... args) throws Exception {initFlowRules();}private void initFlowRules() {List<FlowRule> rules = new ArrayList<>();FlowRule rule = new FlowRule();rule.setResource("myResource"); // 资源名称,与 @SentinelResource 注解中的 value 对应rule.setGrade(RuleConstant.FLOW_GRADE_QPS); // 流控类型:QPSrule.setCount(2); // QPS 阈值为 2rules.add(rule);FlowRuleManager.loadRules(rules); // 加载规则}
}
FlowRule
:FlowRule
对象表示一个流控规则。rule.setResource("myResource")
: 指定规则应用于哪个资源,需要与@SentinelResource
注解或编程式 API 中定义的资源名称一致。rule.setGrade(RuleConstant.FLOW_GRADE_QPS)
: 设置流控类型为 QPS (每秒请求数)。rule.setCount(2)
: 设置 QPS 阈值为 2,即每秒钟只允许 2 个请求通过。FlowRuleManager.loadRules(rules)
: 加载配置好的规则列表。
步骤 5: 启动 Sentinel 控制台和 Spring Boot 应用
- 启动 Sentinel 控制台: 下载 Sentinel 控制台的 JAR 包,并使用
java -jar sentinel-dashboard.jar
命令启动。 默认访问地址为http://localhost:8080
,默认用户名密码都是sentinel
。 - 启动 Spring Boot 应用: 启动你的 Spring Boot 应用。
步骤 6: 测试和监控
- 访问受保护的接口: 访问你应用中被
@SentinelResource
或编程式 API 保护的接口。 - 观察 Sentinel 控制台: 在 Sentinel 控制台中,你可以看到你的应用的监控数据,例如 “簇点链路” 中会显示资源的请求量、通过量、拒绝量、平均响应时间等指标。
- 测试流控效果: 尝试以超过你配置的流控阈值的速率访问受保护的接口,你会看到部分请求被 Sentinel 拦截,并返回你在
blockHandler
方法中定义的提示信息。
高级特性 (可选)
Sentinel 还提供了很多高级特性,你可以根据实际需求进行探索和使用,例如:
- 降级规则 (Degrade Rule): 配置熔断降级规则,当服务的错误率或响应时间超过阈值时,自动熔断,防止故障扩散。
- 热点参数限流 (Hot-spot Param Flow Control): 根据请求的热点参数进行限流,例如根据用户 ID、商品 ID 等。
- 系统规则 (System Rule): 从系统全局负载角度进行保护,例如根据 CPU 使用率、Load、内存使用率等进行自适应限流。
- 授权规则 (Authority Rule): 进行黑白名单授权控制,限制特定来源的请求访问。
- 持久化规则 (Rule Persistence): 将规则持久化到 Nacos、ZooKeeper、Redis 等配置中心,实现规则的动态更新和集群共享。
- 自定义 BlockHandler 和 Fallback: 更灵活地处理 BlockException 和业务异常,实现更精细的降级策略。
- 集群流控 (Cluster Flow Control): 对集群中的多个实例进行统一的流量控制。
总结
使用 Spring Cloud Alibaba Sentinel 在 Spring Boot 中实现限流、熔断降级是非常简单的。 通过添加依赖、配置 Sentinel 控制台地址、定义受保护的资源、配置规则,你就可以快速为你的 Spring Boot 应用增加一层强大的保护屏障,提升系统的稳定性和容错能力。 Sentinel 提供的可视化控制台和丰富的特性,也使得流量控制和容错管理更加便捷高效。