SpringCloud-Hystrix:服务容错保护

摘要

  微服务架构中,各服务之间可能会有互相调用的关系。当其中一个服务发生故障,可能会使相关联的服务也产生问题,出现雪崩效应。
  针对这种情况,SpringCloud全家桶中加入了Hystrix作为服务容错工具,对故障服务临时处理,返回一个自己预期的、可以处理的结果。

参考文档:http://cloud.spring.io/spring-cloud-static/Finchley.RELEASE/single/spring-cloud.html#_circuit_breaker_hystrix_clients
参考文档:https://github.com/Netflix/Hystrix/wiki
略:13.2-13.3、14-15

正文

Hystrix

  默认情况下,当服务10秒(metrics.rollingStats.timeInMilliseconds)内的20次(circuitBreaker.requestVolumeThreshold)请求失败率超过50%(circuitBreaker.errorThresholdPercentage),在Hystrix就会打开。

如何加入Hystrix

  个人认为:Hystrix的本质是包装原方法,捕获异常原方法执行异常后,调用错误回调方法。通过下面的简单例子演示如何为方法加入Hystrix功能。

  • 加入Hystrix依赖
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
  • 启动类标记@EnableCircuitBreaker注解
@EnableCircuitBreaker
@SpringBootApplication
public class HystrixApplication {
    public static void main(String[] args) {
        new SpringApplicationBuilder(HystrixApplication.class).web(true).run(args);
    }
}
  • 通过@HystrixCommand为方法添加错误回调处理
@Component
public class TestComponent {

    @HystrixCommand(fallbackMethod = "testMethodFallback")
    public Object testMethod(Map<String, Object> parameters) {
        // 省略
    }

    public Object testMethodFallback(Map<String, Object> parameters) {
        // 返回一个可接受的结果
    }
}

  可以通过commandProperties和@HystrixProperty来配置@HystrixCommand的属性。

Hystrix指标流

  Hystrix提供了指标流,可以实时查看服务调用情况。可以通过下面的方式启动指标流。

  • 加入Actuator依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
  • 开启指标流端点
management:
    endpoints:
        web:
            exposure:
                include: hystrix.stream

  启动程序,访问http:localhost:8080/actuator/hystrix.stream即可。

  当使用Hystrix包装Ribbon客户端时,要保证Hystrix超时时间大于Ribbon的超时时间✖️Ribbon重试次数。例如:Ribbon超时时间1秒,重试3次,则Hystrix超时时间大于3秒。
  

猜你喜欢

转载自blog.csdn.net/weixin_38229356/article/details/81048084