1. 程式人生 > >Spring Cloud架構教程 (一)Hystrix監控面板

Spring Cloud架構教程 (一)Hystrix監控面板

下面我們基於之前的示例來結合Hystrix Dashboard實現Hystrix指標資料的視覺化面板,這裡我們將用到下之前實現的幾個應用,包括:

  • eureka-server:服務註冊中心
  • eureka-client:服務提供者
  • eureka-consumer-ribbon-hystrix:使用ribbon和hystrix實現的服務消費者

由於eureka-consumer-ribbon-hystrix專案中的/consumer介面實現使用了@HystrixCommand修飾,所以這個介面的呼叫情況會被Hystrix記錄下來,以用來給斷路器和Hystrix Dashboard使用。斷路器我們在上一篇中已經介紹過了,下面我們來具體說說Hystrix Dashboard的構建。

動手試一試

在Spring Cloud中構建一個Hystrix Dashboard非常簡單,只需要下面四步:

  • 建立一個標準的Spring Boot工程,命名為:hystrix-dashboard。
  • 編輯pom.xml,具體依賴內容如下:
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-parent</artifactId>
<version>Dalston.SR1</version>
<relativePath />
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
  • 為應用主類加上@EnableHystrixDashboard,啟用Hystrix Dashboard功能。
@EnableHystrixDashboard
@SpringCloudApplication
public class HystrixDashboardApplication {
public static void main(String[] args) {
SpringApplication.run(HystrixDashboardApplication.class, args);
}
}
  • 根據實際情況修改application.properties配置檔案,比如:選擇一個未被佔用的埠等,此步非必須。
spring.application.name=hystrix-dashboard
server.port=1301

到這裡我們已經完成了基本配置,接下來我們可以啟動該應用,並訪問:http://localhost:1301/hystrix,我們可以看到如下頁面:

這是Hystrix Dashboard的監控首頁,該頁面中並沒有具體的監控資訊。從頁面的文字內容中我們可以知道,Hystrix Dashboard共支援三種不同的監控方式,依次為:

  • 預設的叢集監控:通過URLhttp://turbine-hostname:port/turbine.stream開啟,實現對預設叢集的監控。
  • 指定的叢集監控:通過URLhttp://turbine-hostname:port/turbine.stream?cluster=[clusterName]開啟,實現對clusterName叢集的監控。
  • 單體應用的監控:通過URLhttp://hystrix-app:port/hystrix.stream開啟,實現對具體某個服務例項的監控。

前兩者都對叢集的監控,需要整合Turbine才能實現,這部分內容我們將在下一篇中做詳細介紹。在本節中,我們主要實現對單個服務例項的監控,所以這裡我們先來實現單個服務例項的監控。

既然Hystrix Dashboard監控單例項節點需要通過訪問例項的/hystrix.stream介面來實現,自然我們需要為服務例項新增這個端點,而新增該功能的步驟也同樣簡單,只需要下面兩步:

  • 在服務例項pom.xml中的dependencies節點中新增spring-boot-starter-actuator監控模組以開啟監控相關的端點,並確保已經引入斷路器的依賴spring-cloud-starter-hystrix
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
  • 確保在服務例項的主類中已經使用@EnableCircuitBreaker@EnableHystrix註解,開啟了斷路器功能。

到這裡已經完成了所有的配置,我們可以在Hystrix Dashboard的首頁輸入http://localhost:2101/hystrix.stream,已啟動對“eureka-consumer-ribbon-hystrix”的監控,點選“Monitor Stream”按鈕,此時我們可以看到如下頁面:

在對該頁面介紹前,我們先看看在首頁中我們還沒有介紹的兩外兩個引數:

  • Delay:該引數用來控制伺服器上輪詢監控資訊的延遲時間,預設為2000毫秒,我們可以通過配置該屬性來降低客戶端的網路和CPU消耗。
  • Title:該引數對應了上圖頭部標題Hystrix Stream之後的內容,預設會使用具體監控例項的URL,我們可以通過配置該資訊來展示更合適的標題。原始碼來源