1. @HystrixCommand
首先,我们从@HystrixCommand注解入手
@HystrixCommand(fallbackMethod = "fallBack")
public String hiService() {
return restTemplate.getForObject("http://provider/zone?",String.class);
}
@HystrixCommand注解会为当前方法创建一个HystrixCommand对象,这个类的主要作用是命令模式中对于Command的封装,执行命令有如下两个方法:
//用于异步请求,返回的是Future对象,包含服务执行结束时会返回的结果对象。
public Future<R> queue() {
/*
* The Future returned by Observable.toBlocking().toFuture() does not implement the
* interruption of the execution thread when the "mayInterrupt" flag of Future.cancel(boolean) is set to true;
* thus, to comply with the contract of Future, we must wrap around it.
*/
final Future<R> delegate = toObservable().toBlocking().toFuture();
final Future<R> f = new Future<R>() {
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
if (delegate.isCancelled()) {
return false;
}
if (HystrixCommand.this.getProperties().executionIsolationThreadInterruptOnFutureCancel().get()) {
interruptOnFutureCancel.compareAndSet(false, mayInterruptIfRunning);
}
final boolean res = delegate.cancel(interruptOnFutureCancel.get());
if (!isExecutionComplete() && interruptOnFutureCancel.get()) {
final Thread t = executionThread.get();
if (t != null && !t.equals(Thread.currentThread())) {
t.interrupt();
}
}
return res;
}
@Override
public boolean isCancelled() {
return delegate.isCancelled();
}
@Override
public boolean isDone() {
return delegate.isDone();
}
@Override
public R get() throws InterruptedException, ExecutionException {
return delegate.get();
}
@Override
public R get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
return delegate.get(timeout, unit);
}
};
/* special handling of error states that throw immediately */
if (f.isDone()) {
try {
f.get();
return f;
} catch (Exception e) {
Throwable t = decomposeException(e);
if (t instanceof HystrixBadRequestException) {
return f;
} else if (t instanceof HystrixRuntimeException) {
HystrixRuntimeException hre = (HystrixRuntimeException) t;
switch (hre.getFailureType()) {
case COMMAND_EXCEPTION:
case TIMEOUT:
// we don't throw these types from queue() only from queue().get() as they are execution errors
return f;
default:
// these are errors we throw from queue() as they as rejection type errors
throw hre;
}
} else {
throw Exceptions.sneakyThrow(t);
}
}
}
return f;
}
//用于同步执行,从依赖服务返回单一对象结果;调用的是queue.get
public R execute() {
try {
return queue().get();
} catch (Exception e) {
throw Exceptions.sneakyThrow(decomposeException(e));
}
}
除去HystrixCommand,还有HystrixObservableCommand,该类主要实现两个方法:
- observe() 这是一个热观察
- toObservable() 这是一个冷观察
实际上,excute() 的实现是queue(),而queue中,我们可以看到有如下:
//使用了冷观察;并且转化成为Future异步对象。
final Future<R> delegate = toObservable().toBlocking().toFuture();
因此,我们可以知道,Hstrix命令的运行有如下两个重要部分:
- 事件源处理(冷、热观察模式)
- 同、异步处理(同步等待返回结果,异步利用Future对象,可以异步处理其它工作,并且最后获取future中需要的结果返回即可)
以下说一下Hystrix的命令执行,用图说明:
2. HystrixCircuitBreaker断路器
在Hystrix中,断路器概念核心,以下是它的定义:
public interface HystrixCircuitBreaker {
//每个Hystrix命令请求,在执行之前,都会调用这个方法,判断当前是否可以执行。
public boolean allowRequest();
//判断开闭状态
public boolean isOpen();
//当断路器处于半开状态,且命令运行成功,则用于关闭断路器
void markSuccess();
}
断路器的实现有多个,采用内部类实现:
//都不实现
static class NoOpCircuitBreaker implements HystrixCircuitBreaker {
@Override
public boolean allowRequest() {
return true;
}
@Override
public boolean isOpen() {
return false;
}
@Override
public void markSuccess() {
}
}
//默认实现
static class HystrixCircuitBreakerImpl implements HystrixCircuitBreaker {
private final HystrixCommandProperties properties;
private final HystrixCommandMetrics metrics;
/* track whether this circuit is open/closed at any given point in time (default to false==closed) */
private AtomicBoolean circuitOpen = new AtomicBoolean(false);
/* when the circuit was marked open or was last allowed to try a 'singleTest' */
private AtomicLong circuitOpenedOrLastTestedTime = new AtomicLong();
//还有具体几个方法的实现。
}
对于断路器来说,断路器会根据本身的状态,即断路器是否开启,来决定这个HystrixCommand命令是否执行,还是调用fallBack进行降级,断路器开启和关闭的度量标准如下,由度量对象metrics获取healthCount进行判断,这个时间窗口默认为10S:
- QPS在预设的阈值之内,则返回false,默认为20。
- 如果错误请求百分比,在预设阈值之下,则返回false。
源码如下:
@Override
public boolean isOpen() {
if (circuitOpen.get()) {
return true;
}
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 {
return true;
}
}
}
判断是否允许:
@Override
public boolean allowRequest() {
//这个地方要注意,我们看到了,强制开启的优先级大于强制关闭。
if (properties.circuitBreakerForceOpen().get()) {
return false;
}
if (properties.circuitBreakerForceClosed().get()) {
isOpen();
return true;
}
//这里通过两个方法的结合使用,实现关闭、开启的切换
return !isOpen() || allowSingleTest();
}
//这个方法的功能是尝试允许命令请求;
public boolean allowSingleTest() {
long timeCircuitOpenedOrWasLastTested = circuitOpenedOrLastTestedTime.get();
// 1) if the circuit is open
// 2) and it's been longer than 'sleepWindow' since we opened the circuit
if (circuitOpen.get() && System.currentTimeMillis() > timeCircuitOpenedOrWasLastTested + properties.circuitBreakerSleepWindowInMilliseconds().get()) {
// We push the 'circuitOpenedTime' ahead by 'sleepWindow' since we have allowed one request to try.
// If it succeeds the circuit will be closed, otherwise another singleTest will be allowed at the end of the 'sleepWindow'.
if (circuitOpenedOrLastTestedTime.compareAndSet(timeCircuitOpenedOrWasLastTested, System.currentTimeMillis())) {
//尝试允许请求,则使得断路器处于半开状态。
return true;
}
}
return false;
}
以上是允许请求的实现:
- 通过allowSingleTest,尝试允许请求访问。
- 通过设置休眠时间,在休眠时间过去之后,则将断路器处于“半开状态”,这种半开状态,实际是就是允许命令请求的执行,如果执行又失败,或者超时,则又将断路器置于全开状态;并且在休眠时间之后,尝试允许,继续处于半开状态。
关闭断路器的实现如下:
public void markSuccess() {
if (circuitOpen.get()) {
//关闭断路器
if (circuitOpen.compareAndSet(true, false)) {
//win the thread race to reset metrics
//Unsubscribe from the current stream to reset the health counts stream. This only affects the health counts view,
//and all other metric consumers are unaffected by the reset
//重置统计信息
metrics.resetStream();
}
}
}