前言
Sentinel整体项目由多个组件构成,但主要分为sentinel-core和sentinel-dashboard,两者分别作为Sentinel的连接服务和管理控制台。使用Sentinel,我们需要先下载sentinel-dashboard管理控制台,然后在应用中依赖sentinel-core连接管理控制台。
按理说整合过程应该非常简单,然而由于版本不匹配等问题网上几个帖子都不能成功整合sentinel,因此把整合过程写在这记录一下。
具体步骤
1. sentinel-dashboard下载
方式一:
下载jar包
sentinel-1.7.1jar包下载链接
链接:pan.baidu.com/s/1reC7C4sO…
提取码:11gm
方式二:
如果dashboard更新了版本想用新的可以用这个方式
项目地址:https://github.com/alibaba/Sentinel
下载源代码,自己打包使用,不过注意,sentinel-dashboard使用Maven管理整个项目,需要将整体项目全部下载打包。
2. sentinel-dashboard运行
命令行输入:
java -Dserver.port=9000
-Dcsp.sentinel.dashboard.server=localhost:9000
-Dproject.name=sentinel-dashboard
-Dcsp.sentinel.api.port=8092
-jar sentinel-dashboard.jar
解释一下:
Dserver.port sentinel-dashboard的运行端口
Dcsp.sentinel.dashboard.server sentinel-dashboard的运行端口
Dproject.name 用于测试的项目名称,把这个参数加上主要是为了能在启动后看看效果
Dcsp.sentinel.api.port 测试项目的端口
如果你想配置sentinel-dashboard的账号密码,可以再加上
-Dsentinel.dashboard.auth.username=username,设置用户名
-Dsentinel.dashboard.auth.password=password,设置访问密码
命令行启动后,浏览器打开localhost:9000可以看到控制台界面
可以看到测试项目sentinel-dashboard一直在更新qps数据
3. springboot连接
pom添加依赖:
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-core</artifactId>
<version>1.8.6</version>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-transport-simple-http</artifactId>
<version>1.8.1</version>
</dependency>
尽可能与上面的版本保持一致。如果你的项目本身是基于spring cloud,则需要依赖的另一个maven文件。google it
启动参数VM options添加:
-Dcsp.sentinel.dashboard.server=localhost:9000
用以连接控制台,也可以写配置文件(貌似也是在基于springcloud的情况下才有用)
在配置类添加规则试试水:
//定义了每秒最多接收2个请求
private static void initFlowQpsRule() {
List<FlowRule> rules = new ArrayList<>();
FlowRule rule = new FlowRule("testSentinel");
// set limit qps to 2
rule.setCount(1);
rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
rules.add(rule);
FlowRuleManager.loadRules(rules);
}
这里就对资源testSentinel定义了每秒最多两个请求的规则
然后我们把规则用起来,在你的接口处理逻辑外面包一层try-catch:
@PostMapping("/myIndex")
public ApiReturnInfo myIndex(){
try{
//如果被限流则会抛异常,走catch逻辑
Entry entry = SphU.entry("testSentinel");
//业务逻辑
return ApiReturnInfo.getSuccess("helloSentinel success");
}catch (Exception e){
return ApiReturnInfo.getSuccess("helloSentinel error");
}
}
可以先在本地多次请求该接口看看效果,应该会有一两次返回的是"helloSentinel error",如果没有,把先流规则改成最多1秒通过1次试试。
由于已经添加了与控制台连接的启动项配置,所以现在打开控制台,可以看到我们真正项目的流量信息,而由于控制台对于流量信息采用懒加载模式,所以如果你好几秒没有新请求,控制台可能就不展示数据了,所以可以先发起几次请求,再到控制台康康。