Sentinel: 分布式系统的流量防卫兵

Quick Start

下面的例子将展现应用如何 3 步接入 Sentinel。同时,Sentinel 也提供一个所见即所得的控制台,能够实时监控资源以及管理规则。git

1.在应用中引入Sentinel Jar包

注意: Sentinel JAR 包仅支持 Java 6 或者以上版本。github

若是应用使用 pom 工程,则在 pom.xml 文件中加入如下代码便可:工具

<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-core</artifactId>
    <version>x.y.z</version>
</dependency>

若是您未使用依赖管理工具,请到 Maven Center Repository 直接下载 JAR 包。ui

2.定义资源

接下来,把须要控制流量的代码用 Sentinel API SphU.entry("HelloWorld")entry.exit() 包围起来便可。在下面的例子中,咱们将 System.out.println("hello wolrd"); 做为资源,用 API 包围起来。参考代码以下:spa

public static void main(String[] args) {
    initFlowRules();
    while (true) {
        Entry entry = null;
        try {
        entry = SphU.entry("HelloWorld");
            System.out.println("hello world");
    } catch (BlockException e1) {
        System.out.println("block!");
    } finally {
       if (entry != null) {
           entry.exit();
       }
    }
    }
}

完成以上两步后,代码端的改造就完成了。日志

3.定义规则

接下来,经过规则来指定容许该资源经过的请求次数,例以下面的代码定义了资源"hello world"每秒最多只能经过 20 个请求。code

private static void initFlowRules(){
    List<FlowRule> rules = new ArrayList<FlowRule>();
    FlowRule rule = new FlowRule();
    rule.setResource("HelloWorld");
    rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
    // Set limit QPS to 20.
    rule.setCount(20);
    rules.add(rule);
    FlowRuleManager.loadRules(rules);
}

完成上面 3 步,Sentinel 就可以正常工做了。xml

4.检查效果

Demo 运行以后,咱们能够在日志 ~/logs/csp/metrics.log.xXXX 里看到下面的输出:资源

|--timestamp-|------date time----|--resource-|p |block|s |e|rt
1529998904000|2018-06-26 15:41:44|hello world|20|0    |20|0|0
1529998905000|2018-06-26 15:41:45|hello world|20|5579 |20|0|728
1529998906000|2018-06-26 15:41:46|hello world|20|15698|20|0|0
1529998907000|2018-06-26 15:41:47|hello world|20|19262|20|0|0
1529998908000|2018-06-26 15:41:48|hello world|20|19502|20|0|0
1529998909000|2018-06-26 15:41:49|hello world|20|18386|20|0|0
​
p表明经过的请求, block表明被阻止的请求, s表明成功处理的请求个数, e表明用户自定义的议程, rt表明平均相应时长。

能够看到,这个程序每秒稳定输出 "hello world" 20 次,和规则中预先设定的阈值是同样的。get

更详细的说明能够参考: 如何使用

更多的例子能够参考: Demo

5.启动 Sentinel 控制台

Sentinel 同时提供控制台,能够实时监控各个资源的运行状况,而且能够实时地修改限流规则。

更多的信息请参考:控制台

相关文章
相关标签/搜索