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 同時提供控制檯,能夠實時監控各個資源的運行狀況,而且能夠實時地修改限流規則。

更多的信息請參考:控制檯

相關文章
相關標籤/搜索