熔断器HystrixCircuitBreaker

熔断器

  熔断器是Fail-Fast机制的实现,开关能保证服务调用者在调用异常服务时, 快速返回结果, 避免大量的同步等待. 并且熔断器能在一段时间后继续侦测请求执行结果, 提供恢复服务调用的可能。

状态图

      这里写图片描述

  1. “关闭”状态。熔断器处于关闭状态时,请求被通过。如果失败率低于设定阈值,则熔断器保持关闭状态,否则状态切换为打开状态。
  2. “打开”状态。熔断器处于打开状态时,请求被禁止。当熔断器休眠时间结束,状态切换为半开状态。
  3. “半开”状态。熔断器处于半开状态时,只允许一个请求通过。当该请求调用成功时, 熔断器恢复到关闭状态;若该请求失败, 熔断器继续保持打开状态。

isOpen判断逻辑

  1. 通过状态变量circuitOpen判断熔断器是否打开,如果打开则返回,否则执行下一步;
  2. 判断统计窗口内的总请求量是否超过设置阈值,没超过则返回,否则执行下一步;
  3. 判断失败率是否超过设置阈值,超过则将circuitOpen置为true;
        public boolean isOpen() {
            if (circuitOpen.get()) {
                // if we're open we immediately return true and don't bother attempting to 'close' ourself as that is left to allowSingleTest and a subsequent successful test to close
                return true;
            }

            // we're closed, so let's see if errors have made us so we should trip the circuit open
            HealthCounts health = metrics.getHealthCounts();

            // check if we are past the statisticalWindowVolumeThreshold
            if (health.getTotalRequests() < properties.circuitBreakerRequestVolumeThreshold().get()) {
                // we are not past the minimum volume threshold for the statisticalWindow so we'll return false immediately and not calculate anything
                return false;
            }

            if (health.getErrorPercentage() < properties.circuitBreakerErrorThresholdPercentage().get()) {
                return false;
            } else {
                // our failure rate is too high, trip the circuit
                if (circuitOpen.compareAndSet(false, true)) {
                    // if the previousValue was false then we want to set the currentTime
                    circuitOpenedOrLastTestedTime.set(System.currentTimeMillis());
                    return true;
                } else {
                    // How could previousValue be true? If another thread was going through this code at the same time a race-condition could have
                    // caused another thread to set it to true already even though we were in the process of doing the same
                    // In this case, we know the circuit is open, so let the other thread set the currentTime and report back that the circuit is open
                    return true;
                }
            }
        }

参考:

  1. https://segmentfault.com/a/1190000005988895

猜你喜欢

转载自blog.csdn.net/yangguosb/article/details/80825962
今日推荐