断路器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

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