[TOC]
在上兩篇文章中講了,服務提供者 Eureka + 服務消費者 Feign,服務提供者 Eureka + 服務消費者(rest + Ribbon),本篇文章結合,上兩篇文章中代碼進行修改加入 斷路器監控(Hystrix Dashboard)
在微服務架構中,根據業務來拆分成一個個的服務,服務與服務之間可以相互調用(RPC),在Spring Cloud可以用RestTemplate+Ribbon和Feign來調用。為了保證其高可用,單個服務通常會集群部署。由于網絡原因或者自身的原因,服務并不能保證100%可用,如果單個服務出現問題,調用這個服務就會出現線程阻塞,此時若有大量的請求涌入,Servlet容器的線程資源會被消耗完畢,導致服務癱瘓。服務與服務之間的依賴性,故障會傳播,會對整個微服務系統造成災難性的嚴重后果,這就是服務故障的“雪崩”效應。
針對上述問題,在Spring Cloud Hystrix中實現了線程隔離、斷路器等一系列的服務保護功能。它也是基于Netflix的開源框架 Hystrix實現的,該框架目標在于通過控制那些訪問遠程系統、服務和第三方庫的節點,從而對延遲和故障提供更強大的容錯能力。Hystrix具備了服務降級、服務熔斷、線程隔離、請求緩存、請求合并以及服務監控等強大功能。
# 什么是斷路器
斷路器模式源于Martin Fowler的Circuit Breaker一文。“斷路器”本身是一種開關裝置,用于在電路上保護線路過載,當線路中有電器發生短路時,“斷路器”能夠及時的切斷故障電路,防止發生過載、發熱、甚至起火等嚴重后果。
在分布式架構中,斷路器模式的作用也是類似的,當某個服務單元發生故障(類似用電器發生短路)之后,通過斷路器的故障監控(類似熔斷保險絲),向調用方返回一個錯誤響應,而不是長時間的等待。這樣就不會使得線程因調用故障服務被長時間占用不釋放,避免了故障在分布式系統中的蔓延。
# 斷路器示意圖
SpringCloud Netflix實現了斷路器庫的名字叫Hystrix. 在微服務架構下,通常會有多個層次的服務調用. 下面是微服架構下, 瀏覽器端通過API訪問后臺微服務的一個示意圖:
![ hystrix 1][8]
一個微服務的超時失敗可能導致瀑布式連鎖反映,下圖中,Hystrix通過自主反饋實現的斷路器, 防止了這種情況發生。
![ hystrix 2][9]
圖中的服務B因為某些原因失敗,變得不可用,所有對服務B的調用都會超時。當對B的調用失敗達到一個特定的閥值(5秒之內發生20次失敗是Hystrix定義的缺省值), 鏈路就會被處于open狀態, 之后所有所有對服務B的調用都不會被執行, 取而代之的是由斷路器提供的一個表示鏈路open的Fallback消息. Hystrix提供了相應機制,可以讓開發者定義這個Fallbak消息.
open的鏈路阻斷了瀑布式錯誤, 可以讓被淹沒或者錯誤的服務有時間進行修復。這個fallback可以是另外一個Hystrix保護的調用, 靜態數據,或者合法的空值. Fallbacks可以組成鏈式結構,所以,最底層調用其它業務服務的第一個Fallback返回靜態數據.
# 準備工作
在開始加入斷路器之前,我們先拿之前兩篇博客,構建的兩個微服務代碼為基礎,進行下面的操作
**建議先閱讀以下兩篇文章**
[Spring Cloud(四) 服務提供者 Eureka + 服務消費者 Feign](http://www.ymq.io/2017/12/06/spring-cloud-feign/)
[Spring Cloud(三) 服務提供者 Eureka + 服務消費者(rest + Ribbon)](http://www.ymq.io/2017/12/05/spring-cloud-ribbon-rest/)
## Eureka Service
**導入第三篇文章中的項目:作為服務注冊中心**
`spring-cloud-eureka-service`
## Eureka Provider
**導入第三篇文章中的項目:作為服務的提供者**
`spring-cloud-eureka-provider-1`
`spring-cloud-eureka-provider-2`
`spring-cloud-eureka-provider-3`
# Ribbon Hystrix
**在 Ribbon中使用斷路器**
## 修改項目
復制 `spring-cloud-ribbon-consumer` 項目,修改名稱為`spring-cloud-ribbon-consumer-hystrix`
## 添加依賴
在項目`pom` 加上`hystrix`的依賴
```xml
<!-- hystrix 斷路器 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
```
## 服務注冊
在程序的啟動類 `RibbonConsumerApplication` 通過 `@EnableHystrix` 開啟 `Hystrix` 斷路器監控
```java
package io.ymq.example.ribbon.consumer.hystrix;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@EnableHystrix
@EnableDiscoveryClient
@SpringBootApplication
public class RibbonConsumerApplication {
@LoadBalanced
@Bean
RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(RibbonConsumerApplication.class, args);
}
}
```
## 消費提供者方法
修改 `ConsumerController` 類的,`hello` 方法,加上注解`@HystrixCommand(fallbackMethod = "defaultStores")` 該注解對該方法創建了熔斷器的功能
,并指定了`defaultStores`熔斷方法,熔斷方法直接返回了一個字符串, `"feign + hystrix ,提供者服務掛了"`
`@HystrixCommand` 表明該方法為`hystrix`包裹,可以對依賴服務進行隔離、降級、快速失敗、快速重試等等`hystrix`相關功能
該注解屬性較多,下面講解其中幾個
- fallbackMethod 降級方法
- commandProperties 普通配置屬性,可以配置HystrixCommand對應屬性,例如采用線程池還是信號量隔離、熔斷器熔斷規則等等
- ignoreExceptions 忽略的異常,默認HystrixBadRequestException不計入失敗
- groupKey() 組名稱,默認使用類名稱
- commandKey 命令名稱,默認使用方法名
```java
package io.ymq.example.ribbon.consumer.hystrix;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* 描述:調用提供者的 `home` 方法
*
* @author yanpenglei
* @create 2017-12-05 18:53
**/
@RestController
public class ConsumerController {
@Autowired
private RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "defaultStores")
@GetMapping(value = "/hello")
public String hello() {
return restTemplate.getForEntity("http://eureka-provider/", String.class).getBody();
}
public String defaultStores() {
return "Ribbon + hystrix ,提供者服務掛了";
}
}
```
## 測試斷路器
依次啟動項目:
`spring-cloud-eureka-service`
`spring-cloud-eureka-provider-1`
`spring-cloud-eureka-provider-2`
`spring-cloud-eureka-provider-3`
`spring-cloud-ribbon-consumer-hystrix`
啟動該工程后,訪問服務注冊中心,查看服務是否都已注冊成功:[http://localhost:8761/](http://localhost:8761/)
![查看各個服務注冊狀態][11]
**在命令窗口`curl http://localhost:9000/hello`,發現一切正常**
或者瀏覽器`get` 請求`http://localhost:9000/hello` F5 刷新
![eureka-provider 提供者服務響應][22]
**停止 spring-cloud-eureka-provider-1 提供者,端口為:8081服務**
**再次訪問命令窗口`curl http://localhost:9000/hello` ,斷路器已經生效,提示:Ribbon + hystrix ,提供者服務掛了**
![Ribbon + hystrix ,提供者服務掛了][33]
# Feign Hystrix
**在 Feign中使用斷路器**
## 修改項目
復制`spring-cloud-feign-consumer` 項目,修改名稱為`spring-cloud-feign-consumer-hystrix`
## 添加依賴
Feign是自帶斷路器的,如果在`Dalston`版本的`Spring Cloud`中,它沒有默認打開。需要需要在配置文件中配置打開它,本項目我們是不需要打開的
```sh
feign:
hystrix:
enabled: true
```
## 服務注冊
修改 `HomeClient`類 ,`@FeignClient` 注解,加上`fallbackFactory`指定新建的`HystrixClientFallbackFactory` 工廠類
在程序的啟動類 `RibbonConsumerApplication` 通過 `@EnableHystrix` 開啟 Hystrix
```java
package io.ymq.example.feign.consumer.hystrix;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
/**
* 描述: 指定這個接口所要調用的 提供者服務名稱 "eureka-provider"
*
* @author yanpenglei
* @create 2017-12-06 15:13
**/
@FeignClient(value ="eureka-provider",fallbackFactory = HystrixClientFallbackFactory.class)
public interface HomeClient {
@GetMapping("/")
String consumer();
}
```
**新加的類 `HystrixClientFallbackFactory.java`**
```java
package io.ymq.example.feign.consumer.hystrix;
import feign.hystrix.FallbackFactory;
import org.springframework.stereotype.Component;
/**
* 描述:
*
* @author yanpenglei
* @create 2017-12-07 20:37
**/
@Component
public class HystrixClientFallbackFactory implements FallbackFactory<HomeClient> {
@Override
public HomeClient create(Throwable throwable) {
return () -> "feign + hystrix ,提供者服務掛了";
}
}
```
## 測試斷路器
依次啟動項目:
`spring-cloud-eureka-service`
`spring-cloud-eureka-provider-1`
`spring-cloud-eureka-provider-2`
`spring-cloud-eureka-provider-3`
`spring-cloud-feign-consumer-hystrix`
啟動該工程后,訪問服務注冊中心,查看服務是否都已注冊成功:[http://localhost:8761/](http://localhost:8761/)
![查看各個服務注冊狀態][44]
**在命令窗口`curl http://localhost:9000/hello`,發現一切正常**
或者瀏覽器`get` 請求`http://localhost:9000/hello` F5 刷新
![eureka-provider 提供者服務響應][55]
**停止 spring-cloud-eureka-provider-1 提供者,端口為:8081服務**
**再次訪問命令窗口`curl http://localhost:9000/hello` ,斷路器已經生效,提示:Feign + hystrix ,提供者服務掛了**
![Feign + hystrix ,提供者服務掛了][66]
# Hystrix Dashboard
## HD 簡介
`Hystrix Dashboard`在微服務架構中為例保證程序的可用性,防止程序出錯導致網絡阻塞,出現了斷路器模型。斷路器的狀況反應了一個程序的可用性和健壯性,它是一個重要指標。`Hystrix Dashboard`是作為斷路器狀態的一個組件,提供了數據監控和友好的圖形化界面。
## 改造項目
復制項目 `spring-cloud-ribbon-consumer-hystrix`,修改名稱 `spring-cloud-ribbon-consumer-hystrix-dashboard` 在它的基礎上進行改造。`Feign`的改造和這一樣。
在`pom`的工程文件引入相應的依賴:
## 添加依賴
```xml
<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>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
</dependency>
```
## 開啟 HD
修改 `RibbonConsumerApplication.java` 類
在程序的入口`RibbonConsumerApplication`類,加上`@EnableHystrix`注解開啟斷路器,這個是必須的,并且需要在程序中聲明斷路點`@HystrixCommand;`加上`@EnableHystrixDashboard`注解,開啟`HystrixDashboard`
```java
package io.ymq.example.ribbon.consumer.hystrix;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@EnableHystrix
@EnableDiscoveryClient
@EnableHystrixDashboard
@SpringBootApplication
public class RibbonConsumerApplication {
@LoadBalanced
@Bean
RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(RibbonConsumerApplication.class, args);
}
}
```
## 聲明斷路點
聲明斷路點 `@HystrixCommand(fallbackMethod = "defaultStores")`
```java
package io.ymq.example.ribbon.consumer.hystrix;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* 描述:調用提供者的 `home` 方法
*
* @author yanpenglei
* @create 2017-12-05 18:53
**/
@RestController
public class ConsumerController {
@Autowired
private RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "defaultStores")
@GetMapping(value = "/hello")
public String hello() {
return restTemplate.getForEntity("http://eureka-provider/", String.class).getBody();
}
public String defaultStores() {
return "feign + hystrix Dashboard ,提供者服務掛了";
}
}
```
`@HystrixCommand` 表明該方法為`hystrix`包裹,可以對依賴服務進行隔離、降級、快速失敗、快速重試等等`hystrix`相關功能
該注解屬性較多,下面講解其中幾個
- `fallbackMethod` 降級方法
- `commandProperties` 普通配置屬性,可以配置`HystrixCommand`對應屬性,例如采用線程池還是信號量隔離、熔斷器熔斷規則等等
- `ignoreExceptions` 忽略的異常,默認`HystrixBadRequestException`不計入失敗
- `groupKey()` 組名稱,默認使用類名稱
- `commandKey` 命令名稱,默認使用方法名
## 測試服務
依次啟動項目:
`spring-cloud-eureka-service`
`spring-cloud-eureka-provider-1`
`spring-cloud-eureka-provider-2`
`spring-cloud-eureka-provider-3`
`spring-cloud-ribbon-consumer-hystrix-dashboard`
啟動該工程后,訪問服務注冊中心,查看服務是否都已注冊成功:[http://localhost:8761/](http://localhost:8761/)
![查看各個服務注冊狀態][77]
**Hystrix Dashboard 監控**
可以訪問 [http://127.0.0.1:9090/hystrix](http://127.0.0.1:9090/hystrix) ,獲取`Hystrix Dashboard`信息,默認最大打開5個終端獲取監控信息,可以增加`delay`參數指定獲取監控數據間隔時間
在界面依次輸入:`http://127.0.0.1:9000/hystrix.stream` 、`2000` 、`hello` 點確定。可以訪問以下,圖形化監控頁面
![ Hystrix Dashboard][88]
**Hystrix Monitor 圖形化監控頁面**
![ Hystrix Monitor 圖形化監控頁面][99]
[8]: https://www.souyunku.com/images/2017/SpringCloud/hystrix/8.png
[9]: https://www.souyunku.com/images/2017/SpringCloud/hystrix/9.png
[11]: https://www.souyunku.com/images/2017/SpringCloud/hystrix/11.png
[22]: https://www.souyunku.com/images/2017/SpringCloud/hystrix/22.png
[33]: https://www.souyunku.com/images/2017/SpringCloud/hystrix/33.png
[44]: https://www.souyunku.com/images/2017/SpringCloud/hystrix/44.png
[55]: https://www.souyunku.com/images/2017/SpringCloud/hystrix/55.png
[66]: https://www.souyunku.com/images/2017/SpringCloud/hystrix/66.png
[77]: https://www.souyunku.com/images/2017/SpringCloud/hystrix/77.png
[88]: https://www.souyunku.com/images/2017/SpringCloud/hystrix/88.png
[99]: https://www.souyunku.com/images/2017/SpringCloud/hystrix/99.png
# 源碼下載
**GitHub:**[https://github.com/souyunku/spring-cloud-examples/tree/master/spring-cloud-hystrix-dashboard](https://github.com/souyunku/spring-cloud-examples/tree/master/spring-cloud-hystrix-dashboard)
**碼云:**[https://gitee.com/souyunku/spring-cloud-examples/tree/master/spring-cloud-hystrix-dashboard](https://gitee.com/souyunku/spring-cloud-examples/tree/master/spring-cloud-hystrix-dashboard)
- Spring Cloud(一)服務的注冊與發現(Eureka)
- Spring Cloud(二)Consul 服務治理實現
- Spring Cloud(三)服務提供者 Eureka + 服務消費者(rest + Ribbon)
- Spring Cloud(四)服務提供者 Eureka + 服務消費者 Feign
- Spring Cloud(五)斷路器監控(Hystrix Dashboard)
- Spring Cloud(六)服務網關 zuul 快速入門
- Spring Cloud(七)服務網關 Zuul Filter 使用
- Spring Cloud(八)高可用的分布式配置中心 Spring Cloud Config
- Spring Cloud(九)高可用的分布式配置中心 Spring Cloud Config 集成 Eureka 服務
- Spring Cloud(十)高可用的分布式配置中心 Spring Cloud Config 中使用 Refresh
- Spring Cloud(十一)高可用的分布式配置中心 Spring Cloud Bus 消息總線集成(RabbitMQ)