Sentinel 基本使用指南:快速集成与核心功能上手
Sentinel 作为轻量级的流量控制组件,集成过程简单高效,通过少量配置即可实现流量控制、熔断降级等核心功能。本文将详细介绍 Sentinel 在 Spring Cloud Alibaba 环境中的基本使用方法。
核心依赖集成
在 Spring Cloud 项目中,只需引入 Sentinel 的 starter 依赖即可快速集成:
1 | <!-- Spring Cloud Alibaba Sentinel 核心依赖 --> |
spring-cloud-starter-alibaba-sentinel
:包含 Sentinel 核心库和 Spring Cloud 集成逻辑;spring-boot-starter-actuator
:可选依赖,用于通过/actuator/sentinel
端点查看 Sentinel 规则和监控数据。
核心配置(application.yml)
通过配置文件指定 Sentinel 控制台地址及通信端口:
1 | spring: |
配置说明:
dashboard
:Sentinel 控制台的 IP 和端口,客户端会定期向控制台发送心跳和监控数据;port
:客户端启动一个 HTTP 服务,用于接收控制台的规则推送(如流控规则配置);- 若无需服务发现,可移除
nacos.discovery
配置。
启动类配置
Sentinel 无需额外注解,只需标准的 Spring Boot 启动类即可:
1 | import org.springframework.boot.SpringApplication; |
启动服务后,Sentinel 客户端会自动连接控制台,并在控制台注册服务实例。
基本使用:监控与规则配置
1. 触发 Sentinel 监控
Sentinel 采用 “懒加载” 机制,只有当接口被调用后,才会在控制台显示该接口的监控数据。
步骤:
编写一个测试接口:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
public class TestController {
// 测试接口1:基本流量控制
public String hello( String name){
return "Hello, " + name;
}
// 测试接口2:用于熔断降级测试
public int divide(int a, int b) {
if (b == 0) {
throw new IllegalArgumentException("除数不能为0");
}
return a / b;
}
}访问接口:
多次调用http://localhost:端口/hello/World
和http://localhost:端口/divide?a=10&b=2
,触发 Sentinel 监控。在控制台查看:
登录 Sentinel 控制台(http://localhost:8080
),在左侧菜单选择服务名springcloudalibaba-sentinel
,即可看到:- 簇点链路:显示所有被监控的接口(如
/hello/{name}
、/divide
); - 实时监控:展示接口的 QPS、响应时间、异常数等实时指标。
- 簇点链路:显示所有被监控的接口(如
2. 配置流量控制规则
流量控制(限流)是 Sentinel 的核心功能,用于限制接口的 QPS 或并发线程数,避免服务被流量压垮。
步骤:
在控制台进入 “簇点链路”,找到目标接口(如
/hello/{name}
),点击 “流控” 按钮;配置限流规则:
- 资源名:默认是接口路径(如
/hello/{name}
); - 限流模式:选择 “QPS”(限制每秒请求数)或 “线程数”(限制并发线程数);
- 阈值:如设置 QPS 阈值为 5(每秒最多允许 5 次请求);
- 点击 “新增” 完成配置。
- 资源名:默认是接口路径(如
测试限流效果:
快速多次调用/hello/World
,当 QPS 超过阈值时,会收到 Sentinel 返回的默认限流提示:1
Blocked by Sentinel (flow limiting)
3. 配置熔断降级规则
当接口出现高频错误或响应超时,熔断降级规则可自动暂停对该接口的调用,避免级联故障。
步骤:
在 “簇点链路” 中找到
/divide
接口,点击 “降级” 按钮;配置降级规则:
- 资源名:
/divide
; - 降级策略:选择 “异常比例”(错误率超过阈值时降级);
- 阈值:如设置为 0.5(错误率超过 50%);
- 时间窗口:如 10 秒(熔断后 10 秒内不再调用该接口);
- 点击 “新增” 完成配置。
- 资源名:
测试熔断效果:
多次调用/divide?a=10&b=0
(故意触发异常),当错误率超过 50% 后,Sentinel 会熔断该接口,返回默认降级提示:1
Blocked by Sentinel (degrade)
Feign 集成:服务间调用的熔断
若使用 Feign 进行服务间调用,可通过配置启用 Sentinel 熔断,当被调用服务不可用时,执行降级逻辑。
1. 开启 Feign 支持 Sentinel
在application.yml
中添加:
1 | feign: |
2. 定义 Feign 客户端及降级类
1 | import org.springframework.cloud.openfeign.FeignClient; |
3. 使用 Feign 客户端
在业务代码中注入UserFeignClient
并调用,当被调用服务故障时,会自动触发UserFeignFallback
的降级逻辑。
自定义限流 / 降级提示
默认的限流提示(Blocked by Sentinel (flow limiting)
)可通过配置自定义:
1 | import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler; |
总结
Sentinel 的基本使用流程可概括为:
- 引入依赖并配置控制台地址;
- 编写接口并触发监控(调用接口);
- 在控制台配置流控 / 降级规则;
- 集成 Feign 时开启 Sentinel 支持,定义降级逻辑
v1.3.10