斷路器Hystrix的使用

什麼是Hystrix?

Hystrix是Netflix所創造的一個庫,這個庫實現了斷路器的功能。

爲什麼需要斷路器?

假設有3個服務,分別爲:A、B、C,其中A調用B,B調用C,即:A-->B-->C

當C不可用時,會導致調用鏈中的級聯失敗,發生雪崩效應,如下:

A——>B——>C

A——>B——>C

A——>B——>C

紅色爲服務不可用的狀態,可以看到:由於C不可用,導致了A和B都不可用了。這個時候就需要一個機制來避免這樣的狀態發生,當B發現C不可用的時候(如:5秒內請求失敗了20次),將不再請求C服務,而是直接由默認操作來返回特點的值。如下圖(圖片來源):

 可以看到,當斷路器(circuit)打開的時候,請求不發發送給服務提供方(supplier),而是由CircuitBreaker直接返回。

 

下面介紹Hystrix的使用

一、添加依賴

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

二、使用@HystrixCommand註解,並添加Fallback方法

    @GetMapping("/users/hystrix/{id}")
    @HystrixCommand(fallbackMethod = "returnDefaultUser")
    public User findByIdWithHystrix(@PathVariable Long id) {
        User user = this.restTemplate.getForObject("http://microservice-provider-user/users/{id}", User.class, id);
        return user;
    }

    public User returnDefaultUser(Long id) {
        User user = new User();
        user.setUsername("river66");
        return user;
    }

當microservice-provider-user(Application Name)微服務不能訪問時,會調用returnDefaultUser這個回調方法。@HystrixCommand是由“javanica”的庫提供的,這個依賴被包含在了spring-cloud-starter-netflix-hystrix裏面。

<dependency>
    <groupId>com.netflix.hystrix</groupId>
    <artifactId>hystrix-javanica</artifactId>
</dependency>

此外,還可以通過Feign來使用Hystrix的功能,只需要在FeignClient中,用fallback屬性實現類即可,如:

@FeignClient(name = "hello", fallback = HystrixClientFallback.class)
protected interface HystrixClient {
    @RequestMapping(method = RequestMethod.GET, value = "/hello")
    Hello iFailSometimes();
}

static class HystrixClientFallback implements HystrixClient {
    @Override
    public Hello iFailSometimes() {
        return new Hello("fallback");
    }
}

實現FeignClient聲明的接口,再使用fallback屬性指定這個實現類。

其他詳細的功能,請查看Spring-Cloud文檔: https://www.springcloud.cc/spring-cloud-dalston.html#_circuit_breaker_hystrix_clients或者https://spring.io/projects/spring-cloud-netflix#learn

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章