Spring Cloud Alibaba Sentinel 详解
官网
1. Sentinel 安装与配置
(1) 依赖管理
<!-- pom.xml 添加依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!-- 集成Feign时需添加 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel-feign</artifactId>
</dependency>
(2) 启动控制台
-
下载Sentinel控制台:
wget https://github.com/alibaba/Sentinel/releases/download/1.8.3/sentinel-dashboard-1.8.3.jar java -jar sentinel-dashboard-1.8.3.jar
访问:
http://localhost:8080
(默认端口)。 -
Spring Boot应用配置:
# application.yml
spring:
cloud:
sentinel:
transport:
dashboard: localhost:8080 # 控制台地址
port: 8719 # Sentinel客户端端口
eager: true # 启动时加载规则
2. 核心配置文件与注解详解
(1) 配置文件关键项
配置项 | 说明 | 示例 |
---|---|---|
transport.dashboard | Sentinel控制台地址(格式:IP:端口 ) | localhost:8080 |
transport.port | Sentinel客户端通信端口 | 8719 |
eager | 是否在启动时加载规则(需配合Nacos等配置中心) | true |
(2) 核心注解 @SentinelResource
@SentinelResource(
value = "getUser", // 资源名称(必填)
fallback = "handleFallback", // 通用降级方法(异常/限流/熔断)
blockHandler = "handleBlock",// 限流/熔断专用处理方法
exceptionsToIgnore = {IllegalArgumentException.class} // 忽略指定异常
)
public User getUser(String userId) { ... }
// 降级方法示例
private User handleFallback(String userId, Throwable e) {
return new User("Fallback", "N/A");
}
3. 服务雪崩现象与熔断机制
(1) 雪崩现象
- 定义:当大量请求调用故障服务时,导致连锁反应,最终所有服务不可用。
- Sentinel解决方案:通过熔断机制隔离故障服务。
(2) 设置熔断规则
// 代码配置熔断规则
DegradeRule rule = new DegradeRule("getUser");
rule.setCount(10) // 触发熔断的异常次数
.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO) // 按异常比例熔断
.setTimeWindow(10); // 熔断时间窗口(秒)
List<DegradeRule> rules = new ArrayList<>();
rules.add(rule);
DegradeRuleManager.loadRules(rules);
4. 控制台界面操作
(1) 核心功能
- 资源监控:查看QPS、异常率、线程数等指标。
- 规则配置:
- 流控规则:设置QPS、线程数、并发量阈值。
- 熔断降级:设置异常比例/次数触发熔断。
- 系统保护:设置CPU使用率、平均RT阈值。
(2) 示例:在控制台配置限流规则
- 进入
Flow Control
标签页。 - 选择资源(如
getUser
)。 - 配置:
- Metric Type:QPS
- Grade:直接拒绝
- Count:10(每秒最大请求量)
5. 流控(限流)配置示例
(1) 代码配置限流规则
FlowRule rule = new FlowRule("getUser");
rule.setGrade(RuleConstant.FLOW_GRAIN_SECOND) // 按秒统计
.setCount(10) // 每秒最大请求量
.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_WARM_UP); // 渐进式限流
List<FlowRule> rules = new ArrayList<>();
rules.add(rule);
FlowRuleManager.loadRules(rules);
(2) 基于注解的限流处理
@SentinelResource(value = "createUser", blockHandler = "handleBlock")
public User createUser(User user) {
// 业务逻辑
}
private User handleBlock(BlockException e) {
return new User("Blocked", "Too many requests");
}
6. 在OpenFeign中集成Sentinel
(1) 依赖与配置
<!-- 需添加Feign-Sentinel依赖 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel-feign</artifactId>
</dependency>
(2) 定义Feign客户端
@FeignClient(name = "user-service",
url = "http://user-service",
fallbackFactory = UserClientFallbackFactory.class)
public interface UserClient {
@GetMapping("/users/{id}")
User getUser(@PathVariable("id") String userId);
}
@Component
public class UserClientFallbackFactory implements FallbackFactory<UserClient> {
@Override
public UserClient create(Throwable cause) {
return new UserClient() {
@Override
public User getUser(String userId) {
return new User("Fallback", "N/A");
}
};
}
}
(3) 控制台配置Feign资源
在控制台为资源user-service#getUser
设置限流/熔断规则。
7. 完整代码示例
(1) 定义资源并配置熔断
@Service
public class UserService {
@SentinelResource(
value = "getUser",
fallback = "handleFallback",
blockHandler = "handleBlock",
exceptionsToIgnore = {IllegalArgumentException.class}
)
public User getUser(String userId) {
// 模拟远程调用
return restTemplate.getForObject("http://user-service/" + userId, User.class);
}
private User handleFallback(String userId, Throwable e) {
return new User("Fallback", "Service Unavailable");
}
private User handleBlock(String userId, BlockException e) {
return new User("Blocked", "Too many requests");
}
}
(2) 启动类配置
@SpringBootApplication
@EnableFeignClients
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
8. 总结对比表格
功能 | Sentinel实现方式 | 配置/注解 |
---|---|---|
限流(流控) | 基于QPS/线程数/并发量,支持渐进式限流 | @SentinelResource + 控制台/代码配置流控规则 |
熔断 | 根据异常比例或次数触发,支持半开恢复 | @SentinelResource + 控制台/代码配置熔断规则 |
系统保护 | 基于CPU使用率、平均响应时间、负载等全局指标 | 控制台配置系统规则 |
服务雪崩隔离 | 熔断+降级机制隔离故障服务 | @SentinelResource 的 fallback 和 blockHandler 方法 |
OpenFeign集成 | 通过spring-cloud-starter-alibaba-sentinel-feign 自动拦截Feign请求 | 定义FallbackFactory 并标注@FeignClient |
9. 注意事项
- 资源命名规范:建议使用
服务名#方法名
(如user-service#getUser
)便于管理。 - 控制台权限:默认无鉴权,生产环境需配置安全策略。
- 规则持久化:配合Nacos等配置中心实现规则动态更新。
- 日志监控:通过
logging.level.com.alibaba.csp=DEBUG
开启详细日志。
通过以上配置和代码示例,可快速实现服务熔断、限流、雪崩防护,并在OpenFeign中集成Sentinel实现客户端容错。