当执行HystrixCommand时,如果发生命令执行异常、熔断器熔断、信号量超过数量,就会执行降级fallback方法,并返回结果。本质上,当出现以上情况是,执行fallback方法,而不是run方法。
private Observable<R> applyHystrixSemantics(final AbstractCommand<R> _cmd) { if (circuitBreaker.allowRequest()) { ... if (executionSemaphore.tryAcquire()) { try { ... return executeCommandAndObserve(_cmd)//执行run方法,如果异常,执行fallback方法 .doOnError(markExceptionThrown) .doOnTerminate(singleSemaphoreRelease) .doOnUnsubscribe(singleSemaphoreRelease); } catch (RuntimeException e) { return Observable.error(e); } } else { return handleSemaphoreRejectionViaFallback();//执行fallback方法,并返回响应Observable } } else { return handleShortCircuitViaFallback();//执行fallback方法,并返回响应Observable } }
executeCommandAndObserve
private Observable<R> executeCommandAndObserve(final AbstractCommand<R> _cmd) { ... Observable<R> execution; if (properties.executionTimeoutEnabled().get()) { execution = executeCommandWithSpecifiedIsolation(_cmd)//执行run方法。 .lift(new HystrixObservableTimeoutOperator<R>(_cmd)); } else { execution = executeCommandWithSpecifiedIsolation(_cmd); } return execution.doOnNext(markEmits) .doOnCompleted(markOnCompleted) .onErrorResumeNext(handleFallback)//如果执行异常,则执行fallback方法。 .doOnEach(setRequestContext); }