一、Sentinel 简介
Sentinel 是阿里巴巴开源的面向分布式服务框架的流量控制组件,主要以流量为切入点,从流量控制、熔断降级、系统负载保护等多个维度保护服务的稳定性。
核心功能:
- 流量控制:基于 QPS、并发线程数等方式限制流量
- 熔断降级:当服务出现异常时快速失败或返回默认值
- 系统自适应保护:根据系统负载自动保护
- 实时监控:提供 Dashboard 查看运行指标
二、项目集成配置
1. 依赖引入
xml
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
<version>2021.1</version>
</dependency>
2. 配置文件设置
yaml
spring:
cloud:
sentinel:
transport:
dashboard: localhost:8080 # Sentinel 控制台地址
port: 8719 # 客户端监听端口
eager: true # 立即连接控制台
filter:
enabled: true # 启用 Web 过滤器
三、核心注解使用
@SentinelResource 注解详解
java
@SentinelResource(
value = "resourceName", // 资源名称
blockHandler = "blockHandlerMethod", // 限流处理方法
fallback = "fallbackMethod", // 降级处理方法
exceptionsToIgnore = {Exception.class} // 忽略的异常类型
)
四、实际应用示例
1. 基础限流示例
java
@GetMapping("/simple/{id}")
@SentinelResource(
value = "simpleApi",
blockHandler = "simpleBlockHandler",
fallback = "simpleFallback"
)
public ResultBean<String> simpleApi(@PathVariable String id) {
if ("error".equals(id)) {
throw new RuntimeException("业务异常");
}
return ResultBean.success("处理结果: " + id);
}
// 限流处理方法
public ResultBean<String> simpleBlockHandler(String id, BlockException ex) {
log.warn("简单API限流触发: {}", ex.getMessage());
return ResultBean.failed("访问过于频繁,请稍后再试");
}
// 降级处理方法
public ResultBean<String> simpleFallback(String id, Throwable ex) {
log.warn("简单API降级处理: {}", ex.getMessage());
return ResultBean.failed("服务暂时不可用");
}
对于测试大家可以用专业的测试工具JMeter进行调试即可 !
2. 多参数接口限流
java
@PostMapping("/multi-param")
@SentinelResource(
value = "multiParamApi",
blockHandler = "multiParamBlockHandler",
fallback = "multiParamFallback",
exceptionsToIgnore = {IllegalArgumentException.class}
)
public ResultBean<String> multiParamApi(
@RequestParam String userId,
@RequestParam String type,
@RequestBody Map<String, Object> data) {
return ResultBean.success("用户" + userId + "的" + type + "操作成功");
}
五、流量规则配置
编程式规则配置
java
@Configuration
public class SentinelRuleConfig {
@PostConstruct
public void initFlowRules() {
List<FlowRule> rules = new ArrayList<>();
// QPS 限流规则
FlowRule simpleApiRule = new FlowRule();
simpleApiRule.setResource("simpleApi");
simpleApiRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
simpleApiRule.setCount(5); // 每秒最多 5 个请求
simpleApiRule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);
rules.add(simpleApiRule);
// 线程数限流规则
FlowRule highConcurrentRule = new FlowRule();
highConcurrentRule.setResource("highConcurrentApi");
highConcurrentRule.setGrade(RuleConstant.FLOW_GRADE_THREAD);
highConcurrentRule.setCount(20); // 最大并发线程数 20
rules.add(highConcurrentRule);
FlowRuleManager.loadRules(rules);
}
}
六、限流与降级的区别
| 特性 | 限流 (Block Handler) | 降级 (Fallback) |
|---|---|---|
| 触发条件 | 达到流量阈值 | 业务异常或超时 |
| 异常类型 | BlockException | 任意异常 |
| 应用场景 | 防止系统过载 | 保证服务可用性 |
七、最佳实践建议
1. 规则配置策略
- QPS 限流:适用于读操作,控制访问频率
- 线程数限流:适用于写操作,控制并发执行数
- 冷启动:避免系统瞬间被大量请求冲击
2. 监控与运维
- 结合 Sentinel Dashboard 实时查看流量情况
- 定期评估和调整限流阈值
- 记录限流日志便于问题排查
3. 代码设计原则
- 限流处理方法参数必须与原方法一致并添加 BlockException
- 降级方法应提供合理的默认返回值
- 合理使用
exceptionsToIgnore避免不必要的降级
八、总结
通过以上示例可以看出,Sentinel 提供了灵活且强大的流量控制能力:
- 易用性:通过简单的注解即可实现复杂的限流逻辑
- 灵活性:支持多种限流策略和降级方案
- 可维护性:可通过 Dashboard 动态调整规则
- 高可靠性:保障系统在高并发下的稳定性
在微服务架构中,合理使用 Sentinel 可以有效提升系统的容错能力和稳定性,是构建高可用应用的重要工具。