微服务组件--限流框架Spring Cloud Hystrix分析( 六 )

【12】分析降级的逻辑
private Observable<R> getFallbackOrThrowException(final AbstractCommand<R> _cmd, final HystrixEventType eventType, final FailureType failureType, final String message, final Exception originalException) {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 (shouldNotBeWrapped(originalException)){/* executionHook for all errors */Exception e = wrapWithOnErrorHook(failureType, originalException);return Observable.error(e);} else 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>>() {@Overridepublic void call(Notification<? super R> rNotification) {setRequestContextIfNeeded(requestContext);}};final Action1<R> markFallbackEmit = new Action1<R>() {@Overridepublic void call(R r) {if (shouldOutputOnNextEvents()) {executionResult = executionResult.addEvent(HystrixEventType.FALLBACK_EMIT);eventNotifier.markEvent(HystrixEventType.FALLBACK_EMIT, commandKey);}}};final Action0 markFallbackCompleted = new Action0() {@Overridepublic 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>>() {@Overridepublic Observable<R> call(Throwable t) {Exception e = originalException;Exception fe = getExceptionFromThrowable(t);if (fe instanceof UnsupportedOperationException) {long latency = System.currentTimeMillis() - executionResult.getStartTimestamp();logger.debug("No fallback for HystrixCommand. ", fe); // debug only since we're throwing the exception and someone higher will do something with iteventNotifier.markEvent(HystrixEventType.FALLBACK_MISSING, commandKey);executionResult = executionResult.addEvent((int) latency, HystrixEventType.FALLBACK_MISSING);/* executionHook for all errors */e = wrapWithOnErrorHook(failureType, e);return Observable.error(new HystrixRuntimeException(failureType, _cmd.getClass(), getLogMessagePrefix() + " " + message + " and no fallback available.", e, fe));} else {long latency = System.currentTimeMillis() - executionResult.getStartTimestamp();logger.debug("HystrixCommand execution " + failureType.name() + " and fallback failed.", fe);eventNotifier.markEvent(HystrixEventType.FALLBACK_FAILURE, commandKey);executionResult = executionResult.addEvent((int) latency, HystrixEventType.FALLBACK_FAILURE);/* executionHook for all errors */e = wrapWithOnErrorHook(failureType, e);return Observable.error(new HystrixRuntimeException(failureType, _cmd.getClass(), getLogMessagePrefix() + " " + message + " and fallback failed.", e, fe));}}};final TryableSemaphore fallbackSemaphore = getFallbackSemaphore();final AtomicBoolean semaphoreHasBeenReleased = new AtomicBoolean(false);final Action0 singleSemaphoreRelease = new Action0() {@Overridepublic void call() {if (semaphoreHasBeenReleased.compareAndSet(false, true)) {fallbackSemaphore.release();}}};Observable<R> fallbackExecutionChain;//上面那些定义的其实都不会在这里调用,主要是看下面的// acquire a permitif (fallbackSemaphore.tryAcquire()) {try {if (isFallbackUserDefined()) {executionHook.onFallbackStart(this);//HystrixCommand类#getFallbackObservablefallbackExecutionChain = getFallbackObservable();} else {//same logic as above without the hook invocationfallbackExecutionChain = getFallbackObservable();}} catch (Throwable ex) {//If hook or user-fallback throws, then use that as the result of the fallback lookupfallbackExecutionChain = 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);}}}//HystrixCommand类#getFallbackObservable@Overridefinal protected Observable<R> getFallbackObservable() {return Observable.defer(new Func0<Observable<R>>() {@Overridepublic Observable<R> call() {try {//调用GenericCommand类的getFallback方法【子类重新写父类】return Observable.just(getFallback());} catch (Throwable ex) {return Observable.error(ex);}}});}//GenericCommand类#getFallback方法@Overrideprotected Object getFallback() {final CommandAction commandAction = getFallbackAction();if (commandAction != null) {try {return process(new Action() {@OverrideObject execute() {MetaHolder metaHolder = commandAction.getMetaHolder();Object[] args = createArgsForFallback(metaHolder, getExecutionException());return commandAction.executeWithArgs(metaHolder.getFallbackExecutionType(), args);}});} catch (Throwable e) {LOGGER.error(FallbackErrorMessageBuilder.create().append(commandAction, e).build());throw new FallbackInvocationException(unwrapCause(e));}} else {return super.getFallback();}}

经验总结扩展阅读