package com.netflix.hystrix; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import com.netflix.hystrix.HystrixCommandMetrics.HealthCounts; import rx.Subscriber; import rx.Subscription; public interface HystrixCircuitBreaker { boolean allowRequest(); boolean isOpen(); void markSuccess(); void markNonSuccess(); boolean attemptExecution(); class Factory { // String is HystrixCommandKey.name() (we can't use HystrixCommandKey directly as we can't guarantee it implements hashcode/equals correctly) private static ConcurrentHashMap<String, HystrixCircuitBreaker> circuitBreakersByCommand = new ConcurrentHashMap<String, HystrixCircuitBreaker>(); } class HystrixCircuitBreakerImpl implements HystrixCircuitBreaker { } static class NoOpCircuitBreaker implements HystrixCircuitBreaker { } }
下面先看一下该接口的抽象方法:java
allowRequest(): 每一个Hystrix命令的请求都经过它判断是否被执行(已经再也不使用,使用attemptExecution()方法进行判断)
attemptExecution(): 每一个Hystrix命令的请求都经过它判断是否被执行
isOpen(): 返回当前断路器是否打开
markSuccess(): 用来关闭断路器
markNonSuccess: 用来打开断路器ide
下面看一下该接口中的类:ui
Factory: 维护了一个Hystrix命令和HystrixCircuitBreaker的关系的集合ConcurrentHashMap<String, HystrixCircuitBreaker> circuitBreakersByCommand。其中key经过HystrixCommandKey来定义,每个Hystrix命令都须要有一个Key来标识,同时根据这个Key能够找到对应的断路器实例。
NoOpCircuitBreaker: 一个啥都不作的断路器,它容许全部请求经过,而且断路器始终处于闭合状态
HystrixCircuitBreakerImpl:断路器的另外一个实现类。atom
在该类中定义了断路器的五个核心对象:.net
HystrixCommandProperties properties:断路器对应实例的属性集合对象/断路器对应HystrixCommand实例的属性对象
HystrixCommandMetrics metrics:用来让HystrixCommand记录各种度量指标的对象
AtomicReference<Status> status: 用来记录断路器的状态,默认是关闭状态
AtomicLong circuitOpened:断路器打开的时间戳,默认-1,表示断路器未打开
AtomicReference<Subscription> activeSubscription: 记录HystrixCommandcode
对接口的实现以下:对象
@Override public boolean isOpen() { if (properties.circuitBreakerForceOpen().get()) { return true; } if (properties.circuitBreakerForceClosed().get()) { return false; } return circuitOpened.get() >= 0; }
用来判断断路器是否打开或关闭。主要步骤有:接口
若是断路器强制打开,返回true
若是断路器强制关闭,返回false
判断circuitOpened的值,若是大于等于0,返回true, 不然返回falseip