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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值