資深架構師帶你深入認識,Sentinel

Sentinel

分佈式系統的流量哨兵,以流量為切入點,對比 Redis 的哨兵模式可以得出 Sentinel 在微服務中的作用是對流量進行監控與管理,例如流量的控制,熔斷降級,系統負載保護等。

Github:https://github.com/alibaba/Sentinel

Sentinel 的主要特性:

資深架構師帶你深入認識,Sentinel

Sentinel 的開源生態:

資深架構師帶你深入認識,Sentinel

Sentinel 分為兩個部分:

  • 核心庫(Java 客戶端)不依賴任何框架/庫,能夠運行於所有 Java 運行時環境,同時對 Dubbo / Spring Cloud 等框架也有較好的支持。
  • 控制檯(Dashboard)基於 Spring Boot 開發,打包後可以直接運行,不需要額外的 Tomcat 等應用容器。

Quick Start

下面的例子將展示應用如何三步接入 Sentinel。同時,Sentinel 也提供所見即所得的控制檯,可以實時監控資源以及管理規則。

STEP 1. 在應用中引入 Sentinel Jar 包

如果應用使用 pom 工程,則在 pom.xml 文件中加入以下代碼即可:

<code>

<

dependency

>

<

groupId

>

com.alibaba.csp

groupId

>

<

artifactId

>

sentinel-core

artifactId

>

<

version

>

1.7.0

version

>

dependency

>

/<code>

注意: 從 Sentinel 1.5.0 開始僅支持 JDK 1.7 或者以上版本。Sentinel 1.5.0 之前的版本最低支持 JDK 1.6。

STEP 2. 定義資源

接下來,我們把需要控制流量的代碼用 Sentinel API SphU.entry("HelloWorld") 和 entry.exit() 包圍起來即可。在下面的例子中,我們將 System.out.println("hello wolrd"); 作為資源,用 API 包圍起來。參考代碼如下:

<code>

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(); } } } } /<code>

完成以上兩步後,代碼端的改造就完成了。

STEP 3. 定義規則

接下來,通過規則來指定允許該資源通過的請求次數,例如下面的代碼定義了資源 HelloWorld 每秒最多隻能通過 20 個請求。

<code>

private

static

void

initFlowRules

(

)

{ List 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); } /<code>

完成上面 3 步,Sentinel 就能夠正常工作了。

STEP 4. 檢查效果

Demo 運行之後,我們可以在日誌 ~/logs/csp/${appName}-metrics.log.xxx 裡看到下面的輸出:

<code>

|--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 1529998907000|

2018

-

06

-

26

15

:

41

:

47

|HelloWorld|

20

|19262|

20

|0|

0

1529998908000

|2018-06-26 15:41:48|

HelloWorld

|20|

19502

|20|

0

|0 1529998909000|

2018

-

06

-

26

15

:

41

:

49

|HelloWorld|

20

|18386|

20

|0|

0

/<code>

其中 p 代表通過的請求,block 代表被阻止的請求,s 代表成功執行完成的請求個數,e 代表用戶自定義的異常,rt 代表平均響應時長。

可以看到,這個程序每秒穩定輸出 "hello world" 20 次,和規則中預先設定的閾值是一樣的。

STEP 5. 啟動 Sentinel 控制檯

您可以參考 Sentinel 控制檯文檔 啟動控制檯,可以實時監控各個資源的運行情況,並且可以實時地修改限流規則。

資深架構師帶你深入認識,Sentinel


分享到:


相關文章: