java springcloud版b2b2c社交電商spring cloud分佈式微服務 (四) 斷路器(Hystrix)

1、斷路器簡介

Netflix has created a library called Hystrix that implements the circuit breaker pattern. In a microservice architecture it is common to have multiple layers of service calls.spring

. —-摘自官網瀏覽器

電子商務社交平臺源碼請加企鵝求求:三五三六二四七二五九。 Netflix開源了Hystrix組件,實現了斷路器模式,SpringCloud對這一組件進行了整合。 在微服務架構中,一個請求須要調用多個服務是很是常見的,以下圖:bash

HystrixGraph.png

較底層的服務若是出現故障,會致使連鎖故障。當對特定的服務的調用的不可用達到一個閥值(Hystric 是5秒20次) 斷路器將會被打開。架構

HystrixFallback.png

斷路打開後,可用避免連鎖故障,fallback方法能夠直接返回一個固定值。微服務

2、準備工做

這篇文章基於上一篇文章的工程,首先啓動上一篇文章的工程,啓動eureka-server 工程;啓動service-hi工程,它的端口爲8762。ui

3、在ribbon使用斷路器

改造serice-ribbon 工程的代碼,首先在pox.xml文件中加入spring-cloud-starter-hystrix的起步依賴:spa

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>複製代碼

在程序的啓動類ServiceRibbonApplication 加@EnableHystrix註解開啓Hystrix:線程

複製代碼
@SpringBootApplication
@EnableDiscoveryClient
@EnableHystrix
public class ServiceRibbonApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(ServiceRibbonApplication.class, args);
    }
 
    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
 
}複製代碼
複製代碼

改造HelloService類,在hiService方法上加上@HystrixCommand註解。該註解對該方法建立了熔斷器的功能,並指定了fallbackMethod熔斷方法,熔斷方法直接返回了一個字符串,字符串爲」hi,」+name+」,sorry,error!」,代碼以下:rest

複製代碼
@Service
public class HelloService {
 
    @Autowired
    RestTemplate restTemplate;
 
    @HystrixCommand(fallbackMethod = "hiError")
    public String hiService(String name) {
        return restTemplate.getForObject("http://SERVICE-HI/hi?name="+name,String.class);
    }
 
    public String hiError(String name) {
        return "hi,"+name+",sorry,error!";
    }
}複製代碼
複製代碼

啓動:service-ribbon 工程,當咱們訪問http://localhost:8764/hi?name=forezp,瀏覽器顯示:code

hi forezp,i am from port:8762複製代碼

此時關閉 service-hi 工程,當咱們再訪問http://localhost:8764/hi?name=forezp,瀏覽器會顯示:

hi ,forezp,orry,error!複製代碼

這就說明當 service-hi 工程不可用的時候,service-ribbon調用 service-hi的API接口時,會執行快速失敗,直接返回一組字符串,而不是等待響應超時,這很好的控制了容器的線程阻塞。電子商務社交平臺源碼請加企鵝求求:三五三六二四七二五九

相關文章
相關標籤/搜索