7Hystrix 断路器开启 · SpringCloud微服务实战 · 看云

7. Hystrix 断路器开启

导航

本节代码地址


在命令结果没有缓存命中的时候,Hystrix在执行命令前需要检查断路器是否为打开状态:
如果断路器是打开的,那么Hystrix不会执行命令,而是转接到fallback处理逻辑
如果断路器是关闭的,那么Hystrix调到第5步(线程池/请求队列/信号量是否占满),检查是否有可用资源来执行命令
断路器开启:
1.整个链路达到一定的阈值,默认情况下,10秒内产生超过20次请求,则符合第一个条件
2.满足第一个条件的情况下,如果请求的错误百分比大于阈值,则会打开断路器,默认50%

断路器一旦开启就会执行回退方法,不在执行目标方法,而且也不会更新链路的健康信息。

下图显示了通过Hystrix向服务依赖项请求时发生的情况
2bf5c8dbd174e46ae7cd0f11fd776b5a_MD5.webp

  1. 构造一个HystrixCommand或HystrixObservableCommand对象
  2. 执行命令
  3. 响应是否已缓存?
  4. 断路器开了吗?
  5. 线程池/队列/信号量是否已满?
  6. HystrixObservableCommand.construct() 要么 HystrixCommand.run()
  7. 计算电路健康
  8. 获取后备
  9. 返回成功的回应

7.1 接下来我们来开启断路器

新建类FwHystrixCommondCircuitEnable,在代码里设置了10秒内有10次请求,操作这个即满足第一个条件,设置操作时间为500毫秒,但是在run()方法中sleep(800),这样请求都会超时。开启断路器


@Slf4j
public class FwHystrixCommondCircuitEnable {

    public static void main(String[] args) {
        
        ConfigurationManager.getConfigInstance().setProperty(
                "hystrix.command.default.circuitBreaker.requestVolumeThreshold",10);
        for(int i=0;i<15;i++){
            ErrorCommand c=new ErrorCommand();
            c.execute();
            if(c.isCircuitBreakerOpen()) {
                log.info("当前断路器被打开,在第{}索引",i);
            }
        }
    }
    static class ErrorCommand extends HystrixCommand<String>{
        public ErrorCommand(){
            super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"))
                    .andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(500)));
        }
        protected String run() throws InterruptedException{
            Thread.sleep(800);
            return "success";
        }
        protected String getFallback(){
            return "fallback";
        }
    }
}

7.2 运行mainf方法

可以看到从第10 个索引开始,断路器被打开

14:49:23.118 [main] INFO com.yisu.hystrix.without.FwHystrixCommondCircuitEnable - 当前断路器被打开,在第10索引
14:49:23.118 [main] INFO com.yisu.hystrix.without.FwHystrixCommondCircuitEnable - 当前断路器被打开,在第11索引
14:49:23.118 [main] INFO com.yisu.hystrix.without.FwHystrixCommondCircuitEnable - 当前断路器被打开,在第12索引
14:49:23.118 [main] INFO com.yisu.hystrix.without.FwHystrixCommondCircuitEnable - 当前断路器被打开,在第13索引
14:49:23.119 [main] INFO com.yisu.hystrix.without.FwHystrixCommondCircuitEnable - 当前断路器被打开,在第14索引