Netflix的創造了一個調用的庫 Hystrix 實現了斷路器。在微服務架構中,通常有多層服務調用。

底層服務出現故障可能導致用戶級聯故障。當調用特定服務達到一定閾值時(Hystrix中的默認值為5秒內的20次故障),電路打開,不進行通話。在開路的情況下,可以使用備用的方法進行處理。如下圖:

當服務B掛掉或者訪問超時后,調用Fallback
1、pom依賴:
<dependency>
<!-- hystrix 斷路器 -->
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
注意:一定要加上commons-lang3的依賴,不然在訪問的時候,會報找不到 org.apache.commons.lang3.Validate 類的異常
2、入口加上@EnableCircuitBreaker注解,啟動斷路器
@SpringBootApplication @EnableDiscoveryClient @EnableCircuitBreaker //開啟斷路器 public class ConsumerApplication { public static void main(String[] args) { SpringApplication.run(ConsumerApplication.class, args); } }
3、使用RestTemplate調用遠程服務
@RestController public class IndexController { @Autowired private RestTemplate restTemplate; @GetMapping("/find/{id}") public UserEntity findById(@PathVariable Long id) { return restTemplate.getForObject("http://service-provider/find/" + id, UserEntity.class); } /** * 測試hystrix * * 1、調用遠程服務超時后,斷路器打開,調用getOneFallBack (如果遠程服務掛了,會立馬調用getOneFallBack,超時時間不起作用) * 2、超時時間為2000毫秒(默認1秒) */ @GetMapping("/getOne/{id}") @HystrixCommand(fallbackMethod = "getOneFallBack", commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000") }) public UserEntity getOne(@PathVariable Long id) { UserEntity user = restTemplate.getForObject("http://service-provider/find/" + id, UserEntity.class); return user; } /** * 參數跟返回類型必須跟上面的一樣,不然會報找不到該方法的錯 */ public UserEntity getOneFallBack(Long id) { UserEntity user = new UserEntity(); user.setId("1000"); user.setAge(12); return user; } }
@HystrixCommand由名為“javanica”的Netflix contrib庫提供 。Spring Cloud在連接到Hystrix斷路器的代理中使用該注釋自動包裝Spring bean。斷路器計算何時打開和關閉電路,以及在發生故障時應該做什么。該注解屬性較多,下面講解常用的幾個:
1、fallbackMethod 降級方法
2、commandProperties 普通配置屬性,可以配置HystrixCommand對應屬性,例如采用線程池還是信號量隔離、熔斷器熔斷規則等等
對於hystrix的配置,也可以在yml文件中配置。如:
hystrix: command: default: execution: timeout: enabled: true #是否開啟超時(默認開啟) isolation: thread: timeoutInMilliseconds: 5000 #超時時間(默認1000毫秒)
測試結果:
1、service-provider正常時,返回結果正常
2、service-provider掛掉時,立馬調用降級方法 getOneFallBack
3、service-provider的rest服務設個斷點,即調用遠程服務超過設置的超時時間(先讀commanProperties,沒配置再讀yml文件配置)后,開始 調用getOneFallBack
Hystrix儀表板
只要啟用了hystrix功能,就會暴露一個端點hystrix.stream 。訪問 http://localhost:18082/hystrix.stream 可以查看詳細的數據

注:這個頁面會實時不斷輸出新的內容(如果有的話),首次訪問的話,會看到一直ping...,但是沒有任何內容,說明這時服務對應的方法沒人調用,可以訪問getOne方法后,再來看這個頁面。
顯然,一堆密密麻麻的文字,沒有人會喜歡看,spring-cloud早就想到這一點了,提供了一個hystrix-dashboard的功能,可以用圖形化的界面來解讀這些數據。
具體做法:
1、增加pom依賴:
<dependency>
<!-- hystrix-dashboard 斷路器儀表板 -->
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
</dependency>
2、在入口開啟儀表板

3、啟動成功后,訪問 http://localhost:18082/hystrix,出現儀表板首頁:

4、配置好后,點擊 Monitor Stream按鈕,出現監控數據:

每個指標的含義如下圖:

