一、HystrixCircuitBreaker接口的起源
断路器模式的思想来源于Netflix这家公司。Spring cloud是非常贱的,他搞了一个CircuitBreaker接口,搞得好像HystrixCircuitBreaker是继承自Spring cloud的CircuitBreaker一样,其实并不是这样的,HystrixCircuitBreaker跟Spring cloud的CircuitBreaker半毛钱的关系都没有,按照出生时间来算,是先有HystrixCircuitBreaker接口,然后才有Spring cloud的CircuitBreaker。
二、HystrixCircuitBreaker的接口定义
/**
* Circuit-breaker logic that is hooked into {@link HystrixCommand} execution and will stop allowing executions if failures have gone past the defined threshold.
* <p>
* The default (and only) implementation will then allow a single retry after a defined sleepWindow until the execution
* succeeds at which point it will again close the circuit and allow executions again.
*/
public interface HystrixCircuitBreaker {
/**
* Every {@link HystrixCommand} requests asks this if it is allowed to proceed or not. It is idempotent and does
* not modify any internal state, and takes into account the half-open logic which allows some requests through
* after the circuit has been opened
*
* @return boolean whether a request should be permitted
*/
boolean allowRequest();
/**
* Whether the circuit is currently open (tripped).
*
* @return boolean state of circuit breaker
*/
boolean isOpen();
/**
* Invoked on successful executions from {@link HystrixCommand} as part of feedback mechanism when in a half-open state.
*/
void markSuccess();
/**
* Invoked on unsuccessful executions from {@link HystrixCommand} as part of feedback mechanism when in a half-open state.
*/
void markNonSuccess();
/**
* Invoked at start of command execution to attempt an execution. This is non-idempotent - it may modify internal
* state.
*/
boolean attemptExecution();
}
HystrixCircuitBreaker接口定义的方法非常的简单,通过源码分析,我们知道,其实第一个方法allowRequest已经不再使用了,取而代之的是attemptExecution方法。allowRequest() 和attemptExecution() 方法,方法目的基本类似,差别在于当断路器满足尝试关闭条件时,前者不会将断路器不会修改状态( CLOSE => HALF-OPEN ),而后者会。很多人估计都很疑惑,HystrixCircuitBreaker到底是被谁调用的呢? 其实很简单,肯定是被Command调用的。至于为什么?我会在后续的博文中给出解释的。从抽象角度看,调用的流程图就是如上所示。