使用
1 添加Maven依赖
<!-- 使用时替换最新的版本 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-core</artifactId>
<version>1.7.1</version>
</dependency>
<!-- Sentinel控制台 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-transport-simple-http</artifactId>
<version>1.7.1</version>
</dependency>
2 启动Sentinel控制台,非必选项,但一般都会使用
- 首先下载Sentinel控制台的jar包,下载当前sentinel对应的版本:https://github.com/alibaba/Sentinel/releases
- 然后运行,可以看到是个Spring Boot应用
java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=sentinel-dashboard -jar ~/Downloads/sentinel-dashboard-1.7.1.jar
3 写sentinel的代码
import java.util.ArrayList;
import java.util.List;
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;
public class HelloSentinel {
public static void main(String[] args) throws InterruptedException {
initRules();
while (true){
try (Entry entry = SphU.entry("HelloWorld")) {
Thread.sleep(10);
// 业务逻辑
System.out.println("hello world");
} catch (BlockException e) {
// 处理被拒绝的请求
System.err.println("blocked");
}
}
}
private static void initRules() {
List<FlowRule> rules = new ArrayList<>();
FlowRule rule = new FlowRule();
rule.setResource("HelloWorld");
// set limit qps to 20
rule.setCount(20);
rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
rules.add(rule);
FlowRuleManager.loadRules(rules);
}
}
4 启动HelloSentinel项目,并且加上启动VM参数
-Dcsp.sentinel.dashboard.server=127.0.0.1:8080
5 去控制台看一下效果,当然也可以看日志,只是不够直观。
- 日志位置:~/logs/csp/${appName}-metrics.log.{date}
image
- 看控制台数据,地址为启动时指定的ip和端口:http://127.0.0.1:8080/。 账号和密码都为:sentinel











网友评论