hystrix的源码文章参考,
hystrixCommand的附属配置如何初始化的(二)
此文章只说了一部分功能,具体细节却没有说清楚,现在我们就一起看看具体细节。
subscribeToStream
真正决定断路器是否从关闭状态中开启的是这段代码:
private Subscription subscribeToStream() {
/*
* This stream will recalculate the OPEN/CLOSED status on every onNext from the health stream
*/
return metrics.getHealthCountsStream()
.observe()
.subscribe(new Subscriber<HealthCounts>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(HealthCounts hc) {
// check if we are past the statisticalWindowVolumeThreshold
if (hc.getTotalRequests() < properties.circuitBreakerRequestVolumeThreshold().get()) {
// we are not past the minimum volume threshold for the stat window,
// so no change to circuit status.
// if it was CLOSED, it stays CLOSED
// if it was half-open, we need to wait for a successful command execution
// if it was open, we need to wait for sleep window to elapse
} else {
if (hc.getErrorPercentage() < properties.circuitBreakerErrorThresholdPercentage().get()) {
//we are not past the minimum error threshold for the stat window,
// so no change to circuit status.
// if it was CLOSED, it stays CLOSED
// if it was half-open, we need to wait for a successful command execution
// if it was open, we need to wait for sleep window to elapse
} else {
// our failure rate is too high, we need to set the state to OPEN
if (status.compareAndSet(Status.CLOSED, Status.OPEN)) {
circuitOpened.set(System.currentTimeMillis());
}
}
}
}
});
}
metrics
metrics是在创建commond的时候获取到的,如下:
会根据commondKey进行缓存,而默认commondkey是执行的path,所以,一个path就有一个对应的metrics
HystrixCommandProperties参数详解
推荐此文章:Hystrix 各个配置
HystrixCircuitBreakerImpl
HystrixCircuitBreakerImpl、HealthCountsStream相关源码与逻辑解析推荐:Hystrix Command执行以及熔断机制整理
在上面文章中补充一点,HystrixCommandCompletionStream的方法:
commandStream.write(commandCompletion);
该方法最终调用了如下的onNext方法:
设置错误的地方
设置错误的代码如下,在netty-common包的DefaultPromise中:
@Override
public Promise<V> setSuccess(V result) {
if (setSuccess0(result)) {
notifyListeners();
return this;
}
throw new IllegalStateException("complete already: " + this);
}
@Override
public boolean trySuccess(V result) {
if (setSuccess0(result)) {
notifyListeners();
return true;
}
return false;
}
@Override
public Promise<V> setFailure(Throwable cause) {
if (setFailure0(cause)) {
notifyListeners();
return this;
}
throw new IllegalStateException("complete already: " + this, cause);
}
有些错误不是根据netty的网络调用的错误来的,例如超时错误,是hystrix自己控制的