在上篇文章Hystrix工作流程解析中,我们整体介绍了Hystrix的工作流程,知道了Hystrix会在下面四种情况下发生降级:

  1. 熔断器打开
  2. 线程池/信号量跑满
  3. 调用超时
  4. 调用失败

本篇文章则介绍一下在发生降级时Hystrix的处理细节,下面的方法异常的处理逻辑:

final Func1<Throwable, Observable<R>> handleFallback = new Func1<Throwable, Observable<R>>() {
@Override
public Observable<R> call(Throwable t) {
circuitBreaker.markNonSuccess();
Exception e = getExceptionFromThrowable(t);
executionResult = executionResult.setExecutionException(e);
if (e instanceof RejectedExecutionException) {
return handleThreadPoolRejectionViaFallback(e);
} else if (t instanceof HystrixTimeoutException) {
return handleTimeoutViaFallback();
} else if (t instanceof HystrixBadRequestException) {
return handleBadRequestByEmittingError(e);
} else {
/*
* Treat HystrixBadRequestException from ExecutionHook like a plain HystrixBadRequestException.
*/
if (e instanceof HystrixBadRequestException) {
eventNotifier.markEvent(HystrixEventType.BAD_REQUEST, commandKey);
return Observable.error(e);
} return handleFailureViaFallback(e);
}
}
};

这里我们拿线程池跑满的逻辑来进行分析

线程池跑满
    private Observable<R> handleThreadPoolRejectionViaFallback(Exception underlying) {
eventNotifier.markEvent(HystrixEventType.THREAD_POOL_REJECTED, commandKey);
threadPool.markThreadRejection();
// use a fallback instead (or throw exception if not implemented)
return getFallbackOrThrowException(this, HystrixEventType.THREAD_POOL_REJECTED, FailureType.REJECTED_THREAD_EXECUTION, "could not be queued for execution", underlying);
}
  1. 第一行发布了一个线程池拒绝的事件
  2. 第二行记录了线程池拒绝的次数
  3. 获取Fallback方法
获取Fallback方法
    final HystrixRequestContext requestContext = HystrixRequestContext.getContextForCurrentThread();
long latency = System.currentTimeMillis() - executionResult.getStartTimestamp();
// record the executionResult
// do this before executing fallback so it can be queried from within getFallback (see See https://github.com/Netflix/Hystrix/pull/144)
executionResult = executionResult.addEvent((int) latency, eventType); if (isUnrecoverable(originalException)) {
logger.error("Unrecoverable Error for HystrixCommand so will throw HystrixRuntimeException and not apply fallback. ", originalException); /* executionHook for all errors */
Exception e = wrapWithOnErrorHook(failureType, originalException);
return Observable.error(new HystrixRuntimeException(failureType, this.getClass(), getLogMessagePrefix() + " " + message + " and encountered unrecoverable error.", e, null));
} else {
if (isRecoverableError(originalException)) {
logger.warn("Recovered from java.lang.Error by serving Hystrix fallback", originalException);
} if (properties.fallbackEnabled().get()) {
/* fallback behavior is permitted so attempt */ final Action1<Notification<? super R>> setRequestContext = new Action1<Notification<? super R>>() {
@Override
public void call(Notification<? super R> rNotification) {
setRequestContextIfNeeded(requestContext);
}
}; final Action1<R> markFallbackEmit = new Action1<R>() {
@Override
public void call(R r) {
if (shouldOutputOnNextEvents()) {
executionResult = executionResult.addEvent(HystrixEventType.FALLBACK_EMIT);
eventNotifier.markEvent(HystrixEventType.FALLBACK_EMIT, commandKey);
}
}
}; final Action0 markFallbackCompleted = new Action0() {
@Override
public void call() {
long latency = System.currentTimeMillis() - executionResult.getStartTimestamp();
eventNotifier.markEvent(HystrixEventType.FALLBACK_SUCCESS, commandKey);
executionResult = executionResult.addEvent((int) latency, HystrixEventType.FALLBACK_SUCCESS);
}
}; final Func1<Throwable, Observable<R>> handleFallbackError = new Func1<Throwable, Observable<R>>() {
@Override
public Observable<R> call(Throwable t) {
/* executionHook for all errors */
Exception e = wrapWithOnErrorHook(failureType, originalException);
Exception fe = getExceptionFromThrowable(t); long latency = System.currentTimeMillis() - executionResult.getStartTimestamp();
Exception toEmit; if (fe instanceof UnsupportedOperationException) {
logger.debug("No fallback for HystrixCommand. ", fe); // debug only since we're throwing the exception and someone higher will do something with it
eventNotifier.markEvent(HystrixEventType.FALLBACK_MISSING, commandKey);
executionResult = executionResult.addEvent((int) latency, HystrixEventType.FALLBACK_MISSING); toEmit = new HystrixRuntimeException(failureType, _cmd.getClass(), getLogMessagePrefix() + " " + message + " and no fallback available.", e, fe);
} else {
logger.debug("HystrixCommand execution " + failureType.name() + " and fallback failed.", fe);
eventNotifier.markEvent(HystrixEventType.FALLBACK_FAILURE, commandKey);
executionResult = executionResult.addEvent((int) latency, HystrixEventType.FALLBACK_FAILURE); toEmit = new HystrixRuntimeException(failureType, _cmd.getClass(), getLogMessagePrefix() + " " + message + " and fallback failed.", e, fe);
} // NOTE: we're suppressing fallback exception here
if (shouldNotBeWrapped(originalException)) {
return Observable.error(e);
} return Observable.error(toEmit);
}
}; final TryableSemaphore fallbackSemaphore = getFallbackSemaphore();
final AtomicBoolean semaphoreHasBeenReleased = new AtomicBoolean(false);
final Action0 singleSemaphoreRelease = new Action0() {
@Override
public void call() {
if (semaphoreHasBeenReleased.compareAndSet(false, true)) {
fallbackSemaphore.release();
}
}
}; Observable<R> fallbackExecutionChain; // acquire a permit
if (fallbackSemaphore.tryAcquire()) {
try {
if (isFallbackUserDefined()) {
executionHook.onFallbackStart(this);
fallbackExecutionChain = getFallbackObservable();
} else {
//same logic as above without the hook invocation
fallbackExecutionChain = getFallbackObservable();
}
} catch (Throwable ex) {
//If hook or user-fallback throws, then use that as the result of the fallback lookup
fallbackExecutionChain = Observable.error(ex);
} return fallbackExecutionChain
.doOnEach(setRequestContext)
.lift(new FallbackHookApplication(_cmd))
.lift(new DeprecatedOnFallbackHookApplication(_cmd))
.doOnNext(markFallbackEmit)
.doOnCompleted(markFallbackCompleted)
.onErrorResumeNext(handleFallbackError)
.doOnTerminate(singleSemaphoreRelease)
.doOnUnsubscribe(singleSemaphoreRelease);
} else {
return handleFallbackRejectionByEmittingError();
}
} else {
return handleFallbackDisabledByEmittingError(originalException, failureType, message);
}
}
}

方法比较长,主要做了以下事情:

  1. 直接看isUnrecoverable方法,判断异常是否为不可恢复异常,如果不可恢复则直接返回失败
  2. 如果是可恢复异常则打印日志
  3. 判断是否开启执行回退方法,如果开启进入步骤4
  4. 创建开始和完成需要发送的两个事件:FALLBACK_EMITFALLBACK_SUCCESS
  5. 创建调用回退方法出现异常时的处理逻辑:handleFallbackError,而这种场景发生的异常只有两种情况:
    1. UnsupportedOperationException异常:未实现getFallback抽象方法
    2. 其他异常
  6. 创建释放信号量的Action:singleSemaphoreRelease
  7. 获取信号量,如果成功执行回退逻辑,也就是调用用户实现的getFallback方法
final protected Observable<R> getFallbackObservable() {
return Observable.defer(new Func0<Observable<R>>() {
@Override
public Observable<R> call() {
try {
return Observable.just(getFallback());
} catch (Throwable ex) {
return Observable.error(ex);
}
}
});
}

对于其他异常类型的处理感兴趣的同学可以继续基于Func1 handleFallback研究

原文地址

Hystrix失败处理逻辑解析的更多相关文章

  1. Hystrix线程隔离技术解析-线程池(转)

    认识Hystrix Hystrix是Netflix开源的一款容错框架,包含常用的容错方法:线程隔离.信号量隔离.降级策略.熔断技术. 在高并发访问下,系统所依赖的服务的稳定性对系统的影响非常大,依赖有 ...

  2. Laravel Exception处理逻辑解析

    Laravel Exception处理逻辑解析 vendor/laravel/framework/src/Illuminate/Foundation/Application.php app首先继承了c ...

  3. Hystrix 配置参数全解析

    code[class*="language-"], pre[class*="language-"] { background-color: #fdfdfd; - ...

  4. Hystrix断路器配置属性解析

    HystrixCommand 配置方式 我们的配置都是基于 HystrixCommand 的,我们通过在方法上添加 @HystrixCommand 注解并配置注解的参数来实现配置,但有的时候一个类里面 ...

  5. ZooKeeper(二):多个端口监听的建立逻辑解析

    ZooKeeper 作为优秀的分布系统协调组件,值得一探究竟.它的启动类主要为: 1. 单机版的zk 使用 ZooKeeperServerMain 2. 集群版的zk 使用 QuorumPeerMai ...

  6. 【C++】C++程序链接失败,无法解析的外部命令,无法解析的外部符号 "private: static class * Object::current"

    C++程序编译结束后,出现链接失败提示: 严重性    代码    说明    项目    文件    行    类别    禁止显示状态错误    LNK2001    无法解析的外部符号 &quo ...

  7. 随便聊聊 SOA & SOAP & WebService 的一些东西,以及客户端开发的代码逻辑解析

    http://blog.csdn.net/hikaliv/article/details/6459779 一天的时间调通了一个 WebService 的 Java 端的 C/S.一个 Android  ...

  8. ZooKeeper(五):事务处理之更新数据逻辑解析

    通过前些文章,我们已经完全从整体架构和数据接入方面理解了ZK的前情工作.接下来,我们就来看ZK的正式工作吧. 本文以 setData /a data 这个命令作为出发点,来观察zk是如何处理来自客户端 ...

  9. 44. 普通对象建一个用户方法,提交时报:失败:建立业务逻辑对象失败:业务逻辑定义更新到数据库失败:ORA-00904: "DEFVERSION": 标识符无效

    LBBIZPROCESSDEFSLBHISTORYBIZPROCESSDEFSLBHISTORYMULTIWFDEFSDESIGNLBHISTORYWORKFLOWDEFSDESIGNLBMULTIW ...

随机推荐

  1. Access Editor Settings 访问编辑器设置

    This topic demonstrates how to access editors in a Detail View using a View Controller. This Control ...

  2. ubuntu 中安装jenkins,基于docker运行jenkins

     本文是在ubuntu环境下安装jenkins,jenkins运行在docker容器中,至于docker如何安装,本文不再描述,大家可以上网查询下,如何安装docker,下面先放上一个使用jenkin ...

  3. 松软科技带你学开发:SQL--FIRST() 函数

    FIRST() 函数(原文链接 松软科技:www.sysoft.net.cn/Article.aspx?ID=3731) FIRST() 函数返回指定的字段中第一个记录的值. 提示:可使用 ORDER ...

  4. js-事件函数调用简化

    // 一般写法 function fn(event) { console.log(event) } div.onclick = function (event) { fn(event) } ===== ...

  5. BurpSuite的基础使用,这个教程有“坑”?

    BurpSuite简介 BurpSuite是一款辅助渗透的工具,可以给我们带来许多便利.Burp给我们提供了简单的HTTP抓包改包,数据枚举模块,以及各种安全漏洞的手动式扫描与爬虫式扫描,还有很多经常 ...

  6. 从华为“鸿蒙”备胎看IT项目建设

    别误会啊,本文并不在讲大家在做IT项目建设的时候学华为做一个备胎系统,以防正主系统崩掉之后能够及时替换到备胎系统里面,不影响业务. 前段时间华为被美帝制裁,然后各家组织对华为各种限制.然而华为整体布局 ...

  7. vue slot内容分发

    当需要让组件组合使用,混合父组件的内容和子组件的模板的时候,就会用到slot.这个过程就叫内容分发. 最为常用的是两种slot:一种是匿名slot, 一种是具名slot. 匿名 很好理解: 就是默认, ...

  8. iOS与JS交互-WKWebView

    iOS移动端应用中,一般都会嵌入网页,在网页中处理的结果需要反馈给iOS让移动端做出相应的处理(例如页面跳转), 1.webview的配置 2.代理方法中拿到事件进行处理 二.JS中的配套出发事件 当 ...

  9. Flutter 基础控件

    内容: Button Image.Icon Switch.Checkbox TextField Form 1.Button RaisedButton 漂浮按钮 FlatButton 扁平按钮 Outl ...

  10. SQL Server存储过程数据库日志文件备份的脚本-干货

    还是拿数据库AAAAAAAA为例子        CREATE PROC [dbo].[p_log_backupAAAAAAAA]    @dbname sysname='',             ...