1. 回顧
上文講解了使用Hystrix為Feign添加回退,並通過Fallback Factory檢查回退原因以及如何為Feign客戶端禁用Hystrix。
2. Hystrix的監控
除實現容錯外,Hystrix還提供了近乎實時的監控。HystrixCommand和HystrixObservableCommand在執行時,
會生成執行結果和運行指標,比如每秒執行的請求數、成功數等,這些監控數據對分析應用系統的狀態很有用。
使用Hystrix的模塊 hystrix-metrics-event-stream ,就可將這些監控的指標信息以 text/event-stream 的格式
暴露給外部系統。spring-cloud-starter-hystrix包含該模塊,在此基礎上,只須為項目添加spring-boot-starter-actuator,
就可使用 /hystrix.stream 端點獲取Hystrix的監控信息了。
> 啟動項目 microservice-discovery-eureka
> 啟動項目 microservice-provider-user
> 修改項目 microservice-consumer-movie-ribbon-hystrix 的啟動類。添加如下方法
/** * 低版本直接啟動即可使用 http://ip:port/hystrix.stream 查看監控信息 * 高版本需要添加本方法方可使用 http://ip:port/hystix.stream 查看監控信息 * * @return */ @Bean public ServletRegistrationBean getServlet() { HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet(); ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet); registrationBean.setLoadOnStartup(1); registrationBean.addUrlMappings("/hystrix.stream"); registrationBean.setName("HystrixMetricsStreamServlet"); return registrationBean; }
> 啟動項目 microservice-consumer-movie-ribbon-hystrix
> 訪問 http://localhost:8010/hystrix.stream,可看到瀏覽器一直處於請求的狀態,頁面一直處於請求狀態,並一直打印ping。
因為此時項目中注解了 @HystrixCommand 的方法還沒有執行,因此也沒有任何的監控數據
> 訪問 http://localhost:8010/user/1 后,再次訪問 http://localhost:8010/hystrix.stream,可看到頁面會重新出現類似於下面的內容。
因為系統會不斷地刷新以獲得實時的監控數據。Hystrix的監控指標非常全面,例如HystrixCommand的名稱、group名稱、
斷路器狀態、錯誤率、錯誤數等。
3. Feign項目的Hystrix監控
啟動前文的microservice-consumer-movie-feign-hystrix-fallback項目,並使用類似的方式測試,然后訪問 http://localhost:8010/hystrix.stream,
發現返回的是404。這是為什么呢?查看項目的依賴樹發現,項目中並沒有hystrix-metrics-event-stream的依賴。
解決方案如下:
> 1. 復制項目 microservice-consumer-movie-feign-hystrix-fallback,將ArtifactId修改為 microservice-consumer-movie-feign-hystrix-fallback-stream.
> 2. 為項目添加依賴
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>
> 3. 在啟動類上添加 @EnableCircuitBreaker ,這樣就使用/hystrix.stream端點監控Hystrix了。
4. 總結
本文講了Hystrix的監控,但是訪問/hystrix.stream端點獲得的數據是以文字形式展示的。很難通過這些數據,一眼看出系統當前的運行狀態。
下文將講解可視化監控數據。敬請期待~~~
5. 參考
周立 --- 《Spring Cloud與Docker微服務架構與實戰》