springCloud學習筆記系列(2)-服務容錯保護:Spring Cloud Hystrix

1.在微服務架構中,咱們將系統拆分爲不少個服務,各個服務之間經過註冊與訂閱的方式相互依賴,因爲各個服務都是在各自的進程中運行,就有可能因爲網絡緣由或者服務自身的問題致使調用故障或延遲,隨着服務的積壓,可能會致使服務崩潰。爲了解決這一系列的問題,斷路器等一系列服務保護機制出現了。spring

  斷路器自己是一種開關保護機制,用於在電路上保護線路過載,當線路中有電器發生短路時,斷路器可以及時切斷故障電路,防止發生過載、發熱甚至起火等嚴重後果。緩存

  在分佈式架構中,斷路器模式的做用也是相似的。網絡

  針對上述問題,Spring Cloud Hystrix 實現了斷路器、線路隔離等一系列服務保護功能。它也是基於 Netflix 的開源框架 Hystrix 實現的,該框架的目標在於經過控制那些訪問遠程系統、服務和第三方庫的節點,從而對延遲和故障提供更強大的容錯能力。Hystrix 具有服務降級、服務熔斷、線程和信號隔離、請求緩存、請求合併以及服務監控等強大功能架構

2.引入依賴(在ribbon的客戶端的依賴的添加)負載均衡

<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-hystrix -->框架

<dependency>分佈式

<groupId>org.springframework.cloud</groupId>微服務

<artifactId>spring-cloud-starter-hystrix</artifactId>this

<version>1.4.6.RELEASE</version>.net

</dependency>

3.在啓動類上添加熔斷器開關注解

SpringBootApplication

@EnableEurekaClient

//開啓熔斷標識

@EnableHystrix

public class OneEurekaClientApplication {

@Bean

@LoadBalanced//讓restTemplate具有Ribbon負載均衡的能力。

public RestTemplate restTemplate()

{

return new RestTemplate();

}

 

 

public static void main(String[] args) {

SpringApplication.run(OneEurekaClientApplication.class, args);

}

}

4.在service要調用的客戶端連接上的方法加上熔斷後的註解

@HystrixCommand(fallbackMethod = "erroMsg")

public String getClientString(){

logger.info("到這裏........................getClientString");

return this.restTemplate.getForObject("http://two-client/home/index", String.class);

 

}

public String erroMsg(){

 

return "您請求的接口出現了一點的錯誤....";

}

5.請求客戶端,把two-client關閉,返回的數據

相關文章
相關標籤/搜索