1. 程式人生 > >玩轉SpringCloud 三.斷路器(Hystrix)RestTemplate+Ribbon和Feign兩種方式

玩轉SpringCloud 三.斷路器(Hystrix)RestTemplate+Ribbon和Feign兩種方式

 此文章基於:

三.斷路器(Hystrix

在微服務架構中,根據業務來拆分成一個個的服務,服務與服務之間可以相互呼叫(RPC),在Spring Cloud可以用來呼叫。為了保證其高可用,單個服務通常會叢集部署。由於網路原因或者自身的原因,服務並不能保證100%可用,如果單個服務出現問題,呼叫這個服務就會出現執行緒阻塞,此時若有大量的請求湧入,Servlet容器的執行緒資源會被消耗完畢,導致服務癱瘓。服務與服務之間的依賴性,故障會傳播,會對整個微服務系統造成災難性的嚴重後果,這就是服務故障的“雪崩”效應

為了解決這個問題,業界提出了斷路器模型。

一、斷路器簡介

Netflix開源了Hystrix元件,實現了斷路器模式,SpringCloud對這一元件進行了整合。 在微服務架構中,一個請求需要呼叫多個服務是非常常見的,如下圖:

較底層的服務如果出現故障,會導致連鎖故障。當對特定的服務的呼叫的不可用達到一個閥值Hystric 是5秒20次) 斷路器將會被開啟。

斷路開啟後,可用避免連鎖故障fallback方法可以直接返回一個固定值。

二、準備工作

啟動demo1 工程;啟動demo2工程,它的埠為8763

三、ribbon使用斷路器

改造demo3 工程的程式碼,首先在pox.xml檔案中加入spring-cloud-starter-netflix-hystrix的起步依賴:

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

在程式的啟動類ServiceRibbonApplication 加@EnableHystrix註解開啟Hystrix:

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

 註解解析:

@EnableHystrix

1.開啟熔斷機制

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

@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!";
    }
}

註解解析:

@HystrixCommand

1. 指定斷路後執行的方法,通過呼叫服務,實現fallback方法

2. 實現在Spring Cloud中使用Hystrix元件:

這就說明當 demo2工程不可用的時候,demo3呼叫 demo2API介面時,會執行快速失敗,直接返回一組字串,而不是等待響應超時,這很好的控制了容器的執行緒阻塞

四、Feign中使用斷路器

基於demo4工程進行改造

Feign是自帶斷路器的,在D版本的Spring Cloud之後,它沒有預設開啟。需要在配置檔案中配置開啟它,在yml最後一行加入:

feign.hystrix.enabled: true

基於demo4工程進行改造,只需要在FeignClient的SchedualServiceHi介面的註解中加上fallback的指定類就行了:

@FeignClient(value = "service-hi",fallback = SchedualServiceHiHystric.class)
public interface SchedualServiceHi {
    @RequestMapping(value = "/hi",method = RequestMethod.GET)
    String sayHiFromClientOne(@RequestParam(value = "name") String name);
}

SchedualServiceHiHystric需要實現SchedualServiceHi 介面,並注入到Ioc容器中,

@Component
public class SchedualServiceHiHystric implements SchedualServiceHi {
    @Override
    public String sayHiFromClientOne(String name) {
        return "sorry "+name;
    }
}

註解解析:

@Component

1. 把普通pojo例項化到spring容器中

2. 泛指各種元件,就是說當我們的類不屬於各種歸類的時候(不屬於@Controller、@Services等的時候),我們就可以使用@Component來標註這個類。

可能出現的錯誤:

那是因為

這裡必須寫實現類.class

這證明斷路器起到作用了。

                          未完,待續。。。