天天看點

springCloud(12):使用Hystrix實作微服務的容錯處理-Hystrix的監控

一、簡介

Hystrix提供了幾乎實時的監控。HystrixCommand和HystrixObserv-ableCommand在執行時,會生成執行結果和運作名額,比如每秒執行的請求數、成功數等,這些監控資料對分析應用系統的狀态很有用。

使用Hystrix的子產品hystrix-metrics-event-stream,就可将這些監控的名額資訊以text/event-stream的格式暴露給外部系統。spring-cloud-starter-hystrix已包含該子產品,在此基礎上,隻須為項目添加spring-boot-starter-actuator,就可使用/hystrix.stream端點獲得Hystrix的監控資訊了。

我們以前的項目spring-hystrix-consumer中就已經包含了spring-cloud-starter-hystrix、spring-boot-starter-actuator,啟動通路:http://localhost:8087/user/1 後,再通路:http://localhost:8087/manage/hystrix.stream ,會重複出現如下内容:

springCloud(12):使用Hystrix實作微服務的容錯處理-Hystrix的監控

這是因為系統會不斷地重新整理以擷取實時的監控資料.Hystrix的監控名額非常全面,例如HystrixCommand的名稱、group名稱、斷路器狀态、錯誤率、錯誤數等。

二、使用Hystrix Dashboard可視化監控資料

前面通過通路/hystrix.stream端點獲得的資料很難一眼看出系統目前的運作狀态,可是使用Hystrix Dashboard可以讓監控資料圖形化、可視化。

操作:

 1、建立一個maven工程,加入Hystrix Dashboard依賴

 2、編寫啟動類,添加@EnableHystrixDashboard注解

 3、配置yml檔案端口8086

測試:

 1、通路http://localhost:8087/hystrix.stream,可看到Hystrix Dashbord的首頁,如下:

springCloud(12):使用Hystrix實作微服務的容錯處理-Hystrix的監控

 2、随意設定一個title,并點選Monitor Stream,這裡Title是:測試,URl是:http://localhost:8087/manage/hystrix.stream

springCloud(12):使用Hystrix實作微服務的容錯處理-Hystrix的監控

注意:此處沒有将Hystrix Dashboard注冊到Eureka Server上,在生産環境中,為了更友善的管理Hystrix Dashboard,可将其注冊到Eureka Server上。

三、使用Turbine聚合監控資料

前面使用的/hystrix.stream端點監控單個微服務。然而在使用微服務架構的應用系統一般會包含多個微服務,每個微服務通常都會部署多個執行個體。如果每次隻能檢視單個執行個體的監控資料,就必須在Hystrix Dashboard上切換想要監控的位址,這顯然很不友善。

3.1、Turbine簡介

Turbine是一個聚合Hystrix監控資料的工具,它可将所有相關/hystrix.stream端點的資料聚合到一個組合的/turbine.stream中,進而讓叢集的監控更加友善。

springCloud(12):使用Hystrix實作微服務的容錯處理-Hystrix的監控

3.2、使用Turbine監控多個微服務

a、建立一個maven項目,添加turbine依賴:

b、在啟動類上添加@EnableTurbine注解

c、編寫application.yml配置檔案

說明:使用上面配置,Turbine會在Eureka Server中找到hystrix-consumer-movie和ribbon-consumer-movie這兩個微服務,并聚合這兩個微服務的監控資料。

d、測試

 第一步:依次啟動Eureka Server(4010)、provide-user(4011)、hystrix-consumer-movie(5012)、ribbon-consumer-movie(5011)、hystrix-turbine(5014)、hystrix-dashboard(5013)

 第二步:通路http://localhost:5012/user/1,讓hystrix-consumer-movie微服務産生監控資料

 第三步:通路http://localhost:5011/user/1,讓ribbon-consumer-movie微服務産生監控資料

 第四步:打開Hystrix Dashboard首頁http://localhost:5013/hystrix.stream,在URL欄填寫http://localhost:5014/turbine.stream,随意填寫title,點選Monitor Stream後出現如下圖:

springCloud(12):使用Hystrix實作微服務的容錯處理-Hystrix的監控

問題:在一些場景下,如微服務與Turbine網絡不通,監控資料怎麼處理? -- 使用消息中間件收集資料

3.3、使用rabbitmq收集監控資料

改造微服務:hystrix-consumer-movie

 a、添加以下依賴

 b、在application.yml中添加

改造:hystrix-turbine

   注意:此處删除spring-cloud-starter-turbine依賴

 b、修改啟動類,将@EnableTurbine改成@EnableTurbineStream

 c、修改application.yml

   同時删除:turbine

 第一步:依次啟動Eureka Server(4010)、provide-user(4011)、hystrix-dashboard(5013)、hystrix-consumer-movie-rabbitmq(5020)、hystrix-turbine-rabbitmq(5021)

 第二步:通路http://localhost:5020/user/1,可正常擷取結果

 第三步:打開Hystrix Dashboard首頁http://localhost:5013/hystrix.stream,在URL欄填寫http://localhost:5021/,随意填寫title,點選Monitor Stream後出現如下圖:

springCloud(12):使用Hystrix實作微服務的容錯處理-Hystrix的監控
上一篇: TCP/IP協定族
下一篇: TCP協定詳解