快速开始
本章节将带你快速上手 Sentinel,只需几步即可完成基本配置。
环境要求
- JDK 1.8 或更高版本
- Maven 或 Gradle(用于依赖管理)
第一步:引入依赖
在项目的 pom.xml 中添加 Sentinel 核心依赖:
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-core</artifactId>
<version>1.8.8</version>
</dependency>
如果使用 Gradle,添加:
implementation 'com.alibaba.csp:sentinel-core:1.8.8'
第二步:定义资源
资源是 Sentinel 进行流量控制的主体。我们可以通过 Sentinel API 将需要保护的代码片段定义为资源:
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
public class QuickStartDemo {
public static void main(String[] args) {
// 初始化规则
initFlowRules();
// 模拟请求
while (true) {
Entry entry = null;
try {
// 定义资源名为 "HelloWorld"
entry = SphU.entry("HelloWorld");
// 业务逻辑
System.out.println("hello world");
} catch (BlockException e) {
// 被限流时的处理逻辑
System.out.println("blocked!");
} finally {
// 确保资源释放
if (entry != null) {
entry.exit();
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
代码说明:
SphU.entry("HelloWorld"):尝试进入名为 "HelloWorld" 的资源,如果被限流会抛出BlockExceptionentry.exit():释放资源,必须放在finally块中确保执行BlockException:当请求被限流或降级时抛出,需要在catch块中处理
第三步:定义规则
规则定义了对资源的保护策略。下面定义一个 QPS 限流规则,限制资源每秒最多处理 20 个请求:
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 java.util.ArrayList;
import java.util.List;
private static void initFlowRules() {
List<FlowRule> rules = new ArrayList<>();
FlowRule rule = new FlowRule();
rule.setResource("HelloWorld"); // 资源名
rule.setGrade(RuleConstant.FLOW_GRADE_QPS); // 限流类型:QPS
rule.setCount(20); // 限流阈值:每秒 20 个请求
rules.add(rule);
FlowRuleManager.loadRules(rules); // 加载规则
}
规则配置说明:
setResource():指定规则作用的资源名称setGrade():限流阈值类型,FLOW_GRADE_QPS表示按 QPS 限流,FLOW_GRADE_THREAD表示按并发线程数限流setCount():限流阈值,QPS 模式下表示每秒允许的请求数
第四步:验证效果
运行程序后,Sentinel 会在用户目录下生成日志文件:
~/logs/csp/${appName}-metrics.log.${date}
日志内容示例:
|--timestamp-|------date time----|-resource-|p |block|s |e|rt
1529998904000|2018-06-26 15:41:44|HelloWorld|20|0 |20|0|0
1529998905000|2018-06-26 15:41:45|HelloWorld|20|5579 |20|0|728
1529998906000|2018-06-26 15:41:46|HelloWorld|20|15698|20|0|0
日志字段说明:
p(passed):通过的请求数block:被限流的请求数s(success):成功执行的请求数e(exception):业务异常数rt:平均响应时间(毫秒)
从日志可以看到,程序每秒稳定输出 "hello world" 20 次,超过阈值的请求被限流。
使用注解定义资源
除了使用 API 方式,Sentinel 还提供了注解方式,更加简洁:
首先添加注解依赖:
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-annotation-cdi-interceptor</artifactId>
<version>1.8.8</version>
</dependency>
使用 @SentinelResource 注解:
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
public class UserService {
@SentinelResource(value = "getUser", blockHandler = "handleBlock")
public String getUser(String userId) {
return "User: " + userId;
}
// 限流时的处理方法,签名需要与原方法一致,最后加一个 BlockException 参数
public String handleBlock(String userId, BlockException e) {
return "系统繁忙,请稍后再试";
}
}
注解说明:
value:资源名称blockHandler:限流时的处理方法名blockHandlerClass:处理方法所在的类(如果不在同一个类中)
启动 Sentinel 控制台
Sentinel 提供了可视化控制台,可以实时监控资源运行情况并动态配置规则。
下载控制台
从 GitHub Release 页面下载控制台 JAR 包:
wget https://github.com/alibaba/Sentinel/releases/download/1.8.8/sentinel-dashboard-1.8.8.jar
启动控制台
java -Dserver.port=8080 \
-Dcsp.sentinel.dashboard.server=localhost:8080 \
-Dproject.name=sentinel-dashboard \
-jar sentinel-dashboard-1.8.8.jar
启动参数说明:
-Dserver.port=8080:控制台端口-Dproject.name=sentinel-dashboard:项目名称
访问控制台
打开浏览器访问 http://localhost:8080,默认用户名和密码都是 sentinel。
客户端接入控制台
要让应用接入控制台,需要添加传输模块依赖:
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-transport-simple-http</artifactId>
<version>1.8.8</version>
</dependency>
启动应用时添加 JVM 参数:
-Dcsp.sentinel.dashboard.server=localhost:8080
接入成功后,在控制台的"机器列表"中可以看到应用,在"簇点链路"中可以看到资源的实时监控数据。
完整示例
下面是一个完整的快速开始示例:
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
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 java.util.ArrayList;
import java.util.List;
public class QuickStartDemo {
public static void main(String[] args) {
// 初始化限流规则
initFlowRules();
// 模拟高并发请求
for (int i = 0; i < 100; i++) {
new Thread(() -> {
while (true) {
Entry entry = null;
try {
entry = SphU.entry("HelloWorld");
System.out.println(Thread.currentThread().getName() + ": hello world");
} catch (BlockException e) {
System.out.println(Thread.currentThread().getName() + ": blocked!");
} finally {
if (entry != null) {
entry.exit();
}
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
break;
}
}
}).start();
}
}
private static void initFlowRules() {
List<FlowRule> rules = new ArrayList<>();
FlowRule rule = new FlowRule();
rule.setResource("HelloWorld");
rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
rule.setCount(20);
rules.add(rule);
FlowRuleManager.loadRules(rules);
}
}
常见问题
1. 为什么控制台看不到数据?
确保:
- 客户端已添加
sentinel-transport-simple-http依赖 - 启动参数正确配置了控制台地址
- 应用有访问量,Sentinel 是懒加载的
2. 规则配置后不生效?
检查:
- 资源名称是否一致
- 规则是否正确加载(通过
FlowRuleManager.getRules()查看) - 是否有多个规则冲突
3. 如何查看实时统计数据?
可以通过 HTTP API 查看:
curl http://localhost:8719/cnode?id=HelloWorld
输出格式:
idx id thread pass blocked success total rt 1m-pass 1m-block 1m-all exception
1 abc 5 20 100 20 120 10 1200 6000 7200 0
下一步
现在你已经掌握了 Sentinel 的基本使用,接下来可以学习: