熔断器HystrixCircuitBreaker

本文介绍了熔断器的工作原理及其在服务调用中的应用。熔断器是一种Fail-Fast机制,可在服务调用出现异常时快速响应并避免长时间等待。文章详细解释了熔断器的三种状态——关闭、打开和半开,并提供了熔断器 isOpen 方法的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

熔断器

  熔断器是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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值