当前位置:   article > 正文

Hystrix源码解析之——Hystrix 各类执行命令_observable.deferdoonterminate

observable.deferdoonterminate

在上一篇文章中最后提到了AbstractCommand是Hystrix中的一个重要的类,于是这篇文章中准备就这个类中关于命令执行的相关方法进行解析。本篇文章将先了解一下observe和toObservable。

一、AbstractCommand#observe 方法

1、com.netflix.hystrix.AbstractCommand#observe

  1. public Observable<R> observe() {
  2. // us a ReplaySubject to buffer the eagerly subscribed-to Observable
  3. ReplaySubject<R> subject = ReplaySubject.create();
  4. // eagerly kick off subscription
  5. final Subscription sourceSubscription = toObservable().subscribe(subject);
  6. // return the subject that can be subscribed to later while the execution has already started
  7. return subject.doOnUnsubscribe(new Action0() {
  8. @Override
  9. public void call() {
  10. sourceSubscription.unsubscribe();
  11. }
  12. });
  13. }

在AbstractCommand#observe方法中,首先是创建一个ReplaySubject对象,rx中的Subject既是一个Observable,也是一个Observer。接着调用toObservable()方法来获取以来执行的Observable,然后通过创建的ReplaySubject对象来订阅该Observable,启动Observable中的相关命令,同时返回ReplaySubject给后续观察者,用于订阅获取执行结果(ReplaySubject会推送所有来自原始Observable的时间给观察者,无论它们何时订阅的)。

这个AbstractCommand#observe方法其实主要依赖于toObservable()方法,HystrixExecutable接口中的execute和queue方法的实现则是依赖于AbstractCommand#observe方法,究其根本也是通过toObservable方法。

2、AbstractCommand#toObservable 方法

  1. public Observable<R> toObservable() {
  2. final AbstractCommand<R> _cmd = this;
  3. //doOnCompleted handler already did all of the SUCCESS work
  4. //doOnError handler already did all of the FAILURE/TIMEOUT/REJECTION/BAD_REQUEST work
  5. // 命令结束时的回调方法,主要是命令调用结束后的清理工作
  6. // 根据 CommandState的执行状态,通过Metrics统计各种状态
  7. final Action0 terminateCommandCleanup = new Action0() {
  8. @Override
  9. public void call() {
  10. if (_cmd.commandState.compareAndSet(CommandState.OBSERVABLE_CHAIN_CREATED, CommandState.TERMINAL)) {
  11. handleCommandEnd(false); //user code never ran
  12. } else if (_cmd.commandState.compareAndSet(CommandState.USER_CODE_EXECUTED, CommandState.TERMINAL)) {
  13. handleCommandEnd(true); //user code did run
  14. }
  15. }
  16. };
  17. //mark the command as CANCELLED and store the latency (in addition to standard cleanup)
  18. // 命令被取消订阅的清理回调方法
  19. final Action0 unsubscribeCommandCleanup = new Action0() {
  20. @Override
  21. public void call() {
  22. if (_cmd.commandState.compareAndSet(CommandState.OBSERVABLE_CHAIN_CREATED, CommandState.UNSUBSCRIBED)) {
  23. if (!_cmd.executionResult.containsTerminalEvent()) {
  24. _cmd.eventNotifier.markEvent(HystrixEventType.CANCELLED, _cmd.commandKey);
  25. try {
  26. executionHook.onUnsubscribe(_cmd);
  27. } catch (Throwable hookEx) {
  28. logger.warn("Error calling HystrixCommandExecutionHook.onUnsubscribe", hookEx);
  29. }
  30. _cmd.executionResultAtTimeOfCancellation = _cmd.executionResult
  31. .addEvent((int) (System.currentTimeMillis() - _cmd.commandStartTimestamp), HystrixEventType.CANCELLED);
  32. }
  33. handleCommandEnd(false); //user code never ran
  34. } else if (_cmd.commandState.compareAndSet(CommandState.USER_CODE_EXECUTED, CommandState.UNSUBSCRIBED)) {
  35. if (!_cmd.executionResult.containsTerminalEvent()) {
  36. _cmd.eventNotifier.markEvent(HystrixEventType.CANCELLED, _cmd.commandKey);
  37. try {
  38. executionHook.onUnsubscribe(_cmd);
  39. } catch (Throwable hookEx) {
  40. logger.warn("Error calling HystrixCommandExecutionHook.onUnsubscribe", hookEx);
  41. }
  42. _cmd.executionResultAtTimeOfCancellation = _cmd.executionResult
  43. .addEvent((int) (System.currentTimeMillis() - _cmd.commandStartTimestamp), HystrixEventType.CANCELLED);
  44. }
  45. handleCommandEnd(true); //user code did run
  46. }
  47. }
  48. };
  49. // 构建执行命令,封装断路器、资源隔离逻辑
  50. final Func0<Observable<R>> applyHystrixSemantics = new Func0<Observable<R>>() {
  51. @Override
  52. public Observable<R> call() {
  53. if (commandState.get().equals(CommandState.UNSUBSCRIBED)) {
  54. return Observable.never();
  55. }
  56. return applyHystrixSemantics(_cmd);
  57. }
  58. };
  59. final Func1<R, R> wrapWithAllOnNextHooks = new Func1<R, R>() {
  60. @Override
  61. public R call(R r) {
  62. R afterFirstApplication = r;
  63. try {
  64. afterFirstApplication = executionHook.onComplete(_cmd, r);
  65. } catch (Throwable hookEx) {
  66. logger.warn("Error calling HystrixCommandExecutionHook.onComplete", hookEx);
  67. }
  68. try {
  69. return executionHook.onEmit(_cmd, afterFirstApplication);
  70. } catch (Throwable hookEx) {
  71. logger.warn("Error calling HystrixCommandExecutionHook.onEmit", hookEx);
  72. return afterFirstApplication;
  73. }
  74. }
  75. };
  76. final Action0 fireOnCompletedHook = new Action0() {
  77. @Override
  78. public void call() {
  79. try {
  80. executionHook.onSuccess(_cmd);
  81. } catch (Throwable hookEx) {
  82. logger.warn("Error calling HystrixCommandExecutionHook.onSuccess", hookEx);
  83. }
  84. }
  85. };
  86. return Observable.defer(new Func0<Observable<R>>() {
  87. @Override
  88. public Observable<R> call() {
  89. /* this is a stateful object so can only be used once */
  90. // 执行状态转换有误时,抛出异常
  91. if (!commandState.compareAndSet(CommandState.NOT_STARTED, CommandState.OBSERVABLE_CHAIN_CREATED)) {
  92. IllegalStateException ex = new IllegalStateException("This instance can only be executed once. Please instantiate a new instance.");
  93. //TODO make a new error type for this
  94. // 命令多次被执行,抛出异常
  95. throw new HystrixRuntimeException(FailureType.BAD_REQUEST_EXCEPTION, _cmd.getClass(), getLogMessagePrefix() + " command executed multiple times - this is not permitted.", ex, null);
  96. }
  97. // 记录命令开始时间
  98. commandStartTimestamp = System.currentTimeMillis();
  99. if (properties.requestLogEnabled().get()) {
  100. // log this command execution regardless of what happened
  101. if (currentRequestLog != null) {
  102. currentRequestLog.addExecutedCommand(_cmd);
  103. }
  104. }
  105. final boolean requestCacheEnabled = isRequestCachingEnabled();
  106. final String cacheKey = getCacheKey();
  107. /* try from cache first */
  108. // 尝试从环境中获取结果
  109. if (requestCacheEnabled) {
  110. HystrixCommandResponseFromCache<R> fromCache = (HystrixCommandResponseFromCache<R>) requestCache.get(cacheKey);
  111. // 如果缓存不为空直接返回缓存结果
  112. if (fromCache != null) {
  113. isResponseFromCache = true;
  114. return handleRequestCacheHitAndEmitValues(fromCache, _cmd);
  115. }
  116. }
  117. // 构建执行命令的Observable
  118. Observable<R> hystrixObservable =
  119. Observable.defer(applyHystrixSemantics)
  120. .map(wrapWithAllOnNextHooks);
  121. Observable<R> afterCache;
  122. // put in cache
  123. // 将Observable封装成HystrixCachedObservable,然后方法哦缓存中
  124. if (requestCacheEnabled && cacheKey != null) {
  125. // wrap it for caching
  126. HystrixCachedObservable<R> toCache = HystrixCachedObservable.from(hystrixObservable, _cmd);
  127. HystrixCommandResponseFromCache<R> fromCache = (HystrixCommandResponseFromCache<R>) requestCache.putIfAbsent(cacheKey, toCache);
  128. if (fromCache != null) {
  129. // another thread beat us so we'll use the cached value instead
  130. toCache.unsubscribe();
  131. isResponseFromCache = true;
  132. return handleRequestCacheHitAndEmitValues(fromCache, _cmd);
  133. } else {
  134. // we just created an ObservableCommand so we cast and return it
  135. afterCache = toCache.toObservable();
  136. }
  137. } else {
  138. afterCache = hystrixObservable;
  139. }
  140. return afterCache
  141. .doOnTerminate(terminateCommandCleanup) // perform cleanup once (either on normal terminal state (this line), or unsubscribe (next line))
  142. .doOnUnsubscribe(unsubscribeCommandCleanup) // perform cleanup once
  143. .doOnCompleted(fireOnCompletedHook);
  144. }
  145. });
  146. }

AbstractCommand#toObservable 方法的代码还是蛮复杂的,在这里就来对其进行一一解析:

  1. 首先通过Observable#defer方法构建并返回Observable。以Observable#defer方式声明的Observable只有当观察者订阅才会真正开始创建,并且为每一个观察创建一个新的Observable,这也就保证了AbstractCommand#toObservable方法返回的Observable对象是纯净的,并没有开始执行命令。
  2. 在构建Observable对象的过程中,先通过commandState查看当前的命令执行状态,保证命令未开始并且每条命令只能执行一次。
  3. 如果允许请求缓存存在的话,将尝试从缓存中获取对应的执行结果,并将其直接返回。
  4. 如果无法获取缓存,将通过applyHystrixSemantics方法构建用于返回的Observable。
  5. 如果允许请求缓存,将Observable放置到缓存中用于下一次调用。
  6. 最后为返回到Observable对象添加定义好的回调方法。

在以上的流程中需要关注两点,一个是HystrixRequestCache,它里面封装了缓存Obsevable的逻辑,另一个则是applyHystrixSemantics回调方法,其内部封装了断路、资源隔离等核心断路器逻辑。

二、HystrixRequestCache 请求缓存

HystrixRequestCache是对Obsevable进行缓存操作,使用每个命令特有的cacheKey对Obsevable进行缓存,通过ConcurrentHashMap保存缓存结果以保证线程安全。

HystrixRequestCache中所缓存的并不是单纯的Obsevable 对象,而是被封装好的HystrixCachedObservable。在HystrixCachedObservable中,可通过ReplaySubject订阅需要缓存的Obsevable,保证了缓存的Obsevable 能够被多次执行,代码如下:

  1. public class HystrixCachedObservable<R> {
  2. protected final Subscription originalSubscription;
  3. protected final Observable<R> cachedObservable;
  4. private volatile int outstandingSubscriptions = 0;
  5. protected HystrixCachedObservable(final Observable<R> originalObservable) {
  6. // 使用 ReplaySubject 订阅原始的 Observable,并返回ReplaySubjec
  7. // 保证其从缓存中取出后,订阅依然能够接收对应事件,命令依然能执行
  8. ReplaySubject<R> replaySubject = ReplaySubject.create();
  9. this.originalSubscription = originalObservable
  10. .subscribe(replaySubject);
  11. this.cachedObservable = replaySubject
  12. .doOnUnsubscribe(new Action0() {
  13. @Override
  14. public void call() {
  15. outstandingSubscriptions--;
  16. if (outstandingSubscriptions == 0) {
  17. originalSubscription.unsubscribe();
  18. }
  19. }
  20. })
  21. .doOnSubscribe(new Action0() {
  22. @Override
  23. public void call() {
  24. outstandingSubscriptions++;
  25. }
  26. });
  27. }
  28. // 对象转换
  29. public static <R> HystrixCachedObservable<R> from(Observable<R> o, AbstractCommand<R> originalCommand) {
  30. return new HystrixCommandResponseFromCache<R>(o, originalCommand);
  31. }
  32. // 将Observable对象转换成HystrixCachedObservable
  33. public static <R> HystrixCachedObservable<R> from(Observable<R> o) {
  34. return new HystrixCachedObservable<R>(o);
  35. }
  36. public Observable<R> toObservable() {
  37. return cachedObservable;
  38. }
  39. // 取消订阅
  40. public void unsubscribe() {
  41. originalSubscription.unsubscribe();
  42. }
  43. }

三、applyHystrixSemantics回调方法

在applyHystrixSemantics回调方法中声明了Observable,它主要是用于判断断路器是否打开,以及尝试获取信号量用于执行命令(仅在信号量隔离模式下生效),代码如下:

  1. private Observable<R> applyHystrixSemantics(final AbstractCommand<R> _cmd) {
  2. // mark that we're starting execution on the ExecutionHook
  3. // if this hook throws an exception, then a fast-fail occurs with no fallback. No state is left inconsistent
  4. // 标记在ExecutionHook中执行
  5. executionHook.onStart(_cmd);
  6. /* determine if we're allowed to execute */
  7. // 判断 HystrixCircuitBreaker 命令是否可以执行
  8. if (circuitBreaker.allowRequest()) {
  9. // 获取信号量
  10. final TryableSemaphore executionSemaphore = getExecutionSemaphore();
  11. final AtomicBoolean semaphoreHasBeenReleased = new AtomicBoolean(false);
  12. // 释放信号量的回调方法
  13. final Action0 singleSemaphoreRelease = new Action0() {
  14. @Override
  15. public void call() {
  16. if (semaphoreHasBeenReleased.compareAndSet(false, true)) {
  17. executionSemaphore.release();
  18. }
  19. }
  20. };
  21. // 标记异常的回调方法,对异常进行推送
  22. final Action1<Throwable> markExceptionThrown = new Action1<Throwable>() {
  23. @Override
  24. public void call(Throwable t) {
  25. eventNotifier.markEvent(HystrixEventType.EXCEPTION_THROWN, commandKey);
  26. }
  27. };
  28. // 尝试获取信号量
  29. if (executionSemaphore.tryAcquire()) {
  30. try {
  31. /* used to track userThreadExecutionTime */
  32. // 标记 executionResult 开始时间
  33. executionResult = executionResult.setInvocationStartTime(System.currentTimeMillis());
  34. // 获取执行命令的 Observable
  35. return executeCommandAndObserve(_cmd)
  36. .doOnError(markExceptionThrown)
  37. .doOnTerminate(singleSemaphoreRelease)
  38. .doOnUnsubscribe(singleSemaphoreRelease);
  39. } catch (RuntimeException e) {
  40. return Observable.error(e);
  41. }
  42. } else {
  43. return handleSemaphoreRejectionViaFallback();
  44. }
  45. } else {
  46. return handleShortCircuitViaFallback();
  47. }
  48. }

AbstractCommand#applyHystrixSemantics 方法中,首先是通过断路器HystrixCircuitBreaker 检查链路中的断路器是否开启,如果开启的话,执行断路器失败的逻辑 AbstractCommand#handleShortCircuitViaFallback 方法。如果断路器未打开,将会尝试获取信号量。如果不能获取信号量,那么执行信号量失败逻辑 AbstractCommand#handleSemaphoreRejectionViaFallback 方法。当上述校验都通过的时候,才会执行回调操作,该回调操作在命令执行结束后以及取消订阅的时候释放信号量。

在解析 AbstractCommand#executeCommandAndObserve 方法之前,先了解一下 ExecutionResult ,它是用来记录命令执行中各种状态的类,代码如下:

  1. public class ExecutionResult {
  2. private final EventCounts eventCounts;
  3. private final Exception failedExecutionException; // 执行失败的时候抛出的异常
  4. private final Exception executionException; // 执行异常
  5. private final long startTimestamp; // 开始执行命令的时间
  6. private final int executionLatency; // run() 方法执行时间,即被 HystrixCommand包装的方法
  7. private final int userThreadLatency; //time elapsed between caller thread submitting request and response being visible to it
  8. private final boolean executionOccurred;
  9. private final boolean isExecutedInThread;
  10. private final HystrixCollapserKey collapserKey;
  11. private static final HystrixEventType[] ALL_EVENT_TYPES = HystrixEventType.values();
  12. private static final int NUM_EVENT_TYPES = ALL_EVENT_TYPES.length;
  13. private static final BitSet EXCEPTION_PRODUCING_EVENTS = new BitSet(NUM_EVENT_TYPES);
  14. private static final BitSet TERMINAL_EVENTS = new BitSet(NUM_EVENT_TYPES);
  15. static {
  16. for (HystrixEventType eventType: HystrixEventType.EXCEPTION_PRODUCING_EVENT_TYPES) {
  17. EXCEPTION_PRODUCING_EVENTS.set(eventType.ordinal());
  18. }
  19. for (HystrixEventType eventType: HystrixEventType.TERMINAL_EVENT_TYPES) {
  20. TERMINAL_EVENTS.set(eventType.ordinal());
  21. }
  22. }
  23. // 省略部分代码
  24. }

通过 ExecutionResult来记录 HystrixCommand在不同执行阶段的状态和相关记录,用于后续的统计和分析。AbstractCommand#applyHystrixSemantics 方法最后将执行AbstractCommand#executeCommandAndObserve 方法为命令的配置执行异常回调方法,从而为命令的执行保航护驾。

四、AbstractCommand#executeCommandAndObserve 方法

AbstractCommand#executeCommandAndObserve方法主要用于为执行命令的 Observable 配置执行失败的回调方法,对执行失败的结果进行记录和处理。代码如下:

  1. private Observable<R> executeCommandAndObserve(final AbstractCommand<R> _cmd) {
  2. final HystrixRequestContext currentRequestContext = HystrixRequestContext.getContextForCurrentThread();
  3. // 标记命令开始执行的回调方法
  4. final Action1<R> markEmits = new Action1<R>() {
  5. @Override
  6. public void call(R r) {
  7. if (shouldOutputOnNextEvents()) {
  8. executionResult = executionResult.addEvent(HystrixEventType.EMIT);
  9. eventNotifier.markEvent(HystrixEventType.EMIT, commandKey);
  10. }
  11. if (commandIsScalar()) {
  12. long latency = System.currentTimeMillis() - executionResult.getStartTimestamp();
  13. eventNotifier.markCommandExecution(getCommandKey(), properties.executionIsolationStrategy().get(), (int) latency, executionResult.getOrderedList());
  14. eventNotifier.markEvent(HystrixEventType.SUCCESS, commandKey);
  15. executionResult = executionResult.addEvent((int) latency, HystrixEventType.SUCCESS);
  16. circuitBreaker.markSuccess();
  17. }
  18. }
  19. };
  20. // 标记命令执行结束的回调方法
  21. final Action0 markOnCompleted = new Action0() {
  22. @Override
  23. public void call() {
  24. if (!commandIsScalar()) {
  25. long latency = System.currentTimeMillis() - executionResult.getStartTimestamp();
  26. eventNotifier.markCommandExecution(getCommandKey(), properties.executionIsolationStrategy().get(), (int) latency, executionResult.getOrderedList());
  27. eventNotifier.markEvent(HystrixEventType.SUCCESS, commandKey);
  28. executionResult = executionResult.addEvent((int) latency, HystrixEventType.SUCCESS);
  29. circuitBreaker.markSuccess();
  30. }
  31. }
  32. };
  33. // 失败回滚逻辑
  34. final Func1<Throwable, Observable<R>> handleFallback = new Func1<Throwable, Observable<R>>() {
  35. @Override
  36. public Observable<R> call(Throwable t) {
  37. Exception e = getExceptionFromThrowable(t);
  38. executionResult = executionResult.setExecutionException(e);
  39. if (e instanceof RejectedExecutionException) {
  40. return handleThreadPoolRejectionViaFallback(e);
  41. } else if (t instanceof HystrixTimeoutException) {
  42. return handleTimeoutViaFallback();
  43. } else if (t instanceof HystrixBadRequestException) {
  44. return handleBadRequestByEmittingError(e);
  45. } else {
  46. /*
  47. * Treat HystrixBadRequestException from ExecutionHook like a plain HystrixBadRequestException.
  48. */
  49. if (e instanceof HystrixBadRequestException) {
  50. eventNotifier.markEvent(HystrixEventType.BAD_REQUEST, commandKey);
  51. return Observable.error(e);
  52. }
  53. return handleFailureViaFallback(e);
  54. }
  55. }
  56. };
  57. // 设置请求上下文
  58. final Action1<Notification<? super R>> setRequestContext = new Action1<Notification<? super R>>() {
  59. @Override
  60. public void call(Notification<? super R> rNotification) {
  61. setRequestContextIfNeeded(currentRequestContext);
  62. }
  63. };
  64. Observable<R> execution;
  65. if (properties.executionTimeoutEnabled().get()) {
  66. execution = executeCommandWithSpecifiedIsolation(_cmd)
  67. .lift(new HystrixObservableTimeoutOperator<R>(_cmd));
  68. } else {
  69. execution = executeCommandWithSpecifiedIsolation(_cmd);
  70. }
  71. return execution.doOnNext(markEmits)
  72. .doOnCompleted(markOnCompleted)
  73. .onErrorResumeNext(handleFallback)
  74. .doOnEach(setRequestContext);
  75. }

在AbstractCommand#executeCommandAndObserve方法中,handleFallback失败回滚回调方法根据执行过程中抛出异常的不同调用不同的方法进行处理。对线程获取失败处理调用 AbstractCommand#handleThreadPoolRejectionViaFallback 方法超时处理调用 AbstractCommand#handleTimeoutViaFallback 方法,远程调用处理失败调用 AbstractCommand#handleBadRequestByEmittingError 方法。Hystrix 自身异常处理调用AbstractCommand#handleFailureViaFallback 方法。此外在 AbstractCommand#applyHystrixSemantics 方法中还有断路失败处理AbstractCommand#handleShortCircuitViaFallback方法和获取信号量失败处理AbstractCommand#handleSemaphoreRejectionViaFallback 方法。至此已经了解了不同执行失败结果将导致不同的调用链路,这在后续还会进行解析。

AbstractCommand#executeCommandAndObserve方法的最后,有调用 AbstractCommand#executeCommandWithSpecifiedIsolation 方法来为命令的执行配置资源隔离和添加超时控制。

五、executeCommandWithSpecifiedIsolation方法

AbstractCommand#executeCommandWithSpecifiedIsolation 方法为命令构成了隔离的执行环境,提供了两中隔离方式:线程隔离和信号量隔离。如果Hystrix配置中开启了超时配置,还会通过Observable#lift 方法来将现有的Observable 转化成添加了超时的Observable对象。

AbstractCommand#executeCommandWithSpecifiedIsolation 方法根据配置中的隔离策略对命令执行采用了不同的资源隔离方式:ExecutionIsolationStrategy.THREA(线程隔离的方式)、ExecutionIsolationStrategy.SEMAPHORE(信号量隔离方式)。代码如下:

  1. if (properties.executionIsolationStrategy().get() == ExecutionIsolationStrategy.THREAD) {
  2. // mark that we are executing in a thread (even if we end up being rejected we still were a THREAD execution and not SEMAPHORE)
  3. return Observable.defer(new Func0<Observable<R>>() {
  4. @Override
  5. public Observable<R> call() {
  6. executionResult = executionResult.setExecutionOccurred();
  7. if (!commandState.compareAndSet(CommandState.OBSERVABLE_CHAIN_CREATED, CommandState.USER_CODE_EXECUTED)) {
  8. return Observable.error(new IllegalStateException("execution attempted while in state : " + commandState.get().name()));
  9. }
  10. // 标记命令通过线程隔离资源执行
  11. metrics.markCommandStart(commandKey, threadPoolKey, ExecutionIsolationStrategy.THREAD);
  12. if (isCommandTimedOut.get() == TimedOutStatus.TIMED_OUT) {
  13. // the command timed out in the wrapping thread so we will return immediately
  14. // and not increment any of the counters below or other such logic
  15. return Observable.error(new RuntimeException("timed out before executing run()"));
  16. }
  17. if (threadState.compareAndSet(ThreadState.NOT_USING_THREAD, ThreadState.STARTED)) {
  18. //we have not been unsubscribed, so should proceed
  19. // 标记线程已经执行
  20. HystrixCounters.incrementGlobalConcurrentThreads();
  21. threadPool.markThreadExecution();
  22. // store the command that is being run
  23. endCurrentThreadExecutingCommand = Hystrix.startCurrentThreadExecutingCommand(getCommandKey());
  24. // 记录是使用线程隔离执行
  25. executionResult = executionResult.setExecutedInThread();
  26. /**
  27. * If any of these hooks throw an exception, then it appears as if the actual execution threw an error
  28. */
  29. try {
  30. executionHook.onThreadStart(_cmd);
  31. executionHook.onRunStart(_cmd);
  32. executionHook.onExecutionStart(_cmd);
  33. return getUserExecutionObservable(_cmd);
  34. } catch (Throwable ex) {
  35. return Observable.error(ex);
  36. }
  37. } else {
  38. //command has already been unsubscribed, so return immediately
  39. return Observable.error(new RuntimeException("unsubscribed before executing run()"));
  40. }
  41. }
  42. }).doOnTerminate(new Action0() {
  43. @Override
  44. public void call() {
  45. if (threadState.compareAndSet(ThreadState.STARTED, ThreadState.TERMINAL)) {
  46. handleThreadEnd(_cmd);
  47. }
  48. if (threadState.compareAndSet(ThreadState.NOT_USING_THREAD, ThreadState.TERMINAL)) {
  49. //if it was never started and received terminal, then no need to clean up (I don't think this is possible)
  50. }
  51. //if it was unsubscribed, then other cleanup handled it
  52. }
  53. //
  54. }).doOnUnsubscribe(new Action0() {
  55. @Override
  56. public void call() {
  57. if (threadState.compareAndSet(ThreadState.STARTED, ThreadState.UNSUBSCRIBED)) {
  58. handleThreadEnd(_cmd);
  59. }
  60. if (threadState.compareAndSet(ThreadState.NOT_USING_THREAD, ThreadState.UNSUBSCRIBED)) {
  61. //if it was never started and was cancelled, then no need to clean up
  62. }
  63. //if it was terminal, then other cleanup handled it
  64. }
  65. // 指定命令在那个线程执行
  66. }).subscribeOn(threadPool.getScheduler(new Func0<Boolean>() {
  67. @Override
  68. public Boolean call() {
  69. return properties.executionIsolationThreadInterruptOnTimeout().get() && _cmd.isCommandTimedOut.get() == TimedOutStatus.TIMED_OUT;
  70. }
  71. }));
  72. } else {
  73. return Observable.defer(new Func0<Observable<R>>() {
  74. @Override
  75. public Observable<R> call() {
  76. executionResult = executionResult.setExecutionOccurred();
  77. if (!commandState.compareAndSet(CommandState.OBSERVABLE_CHAIN_CREATED, CommandState.USER_CODE_EXECUTED)) {
  78. return Observable.error(new IllegalStateException("execution attempted while in state : " + commandState.get().name()));
  79. }
  80. // 标记命令是通过信号量执行
  81. metrics.markCommandStart(commandKey, threadPoolKey, ExecutionIsolationStrategy.SEMAPHORE);
  82. // semaphore isolated
  83. // store the command that is being run
  84. endCurrentThreadExecutingCommand = Hystrix.startCurrentThreadExecutingCommand(getCommandKey());
  85. try {
  86. executionHook.onRunStart(_cmd);
  87. executionHook.onExecutionStart(_cmd);
  88. return getUserExecutionObservable(_cmd); //the getUserExecutionObservable method already wraps sync exceptions, so this shouldn't throw
  89. } catch (Throwable ex) {
  90. //If the above hooks throw, then use that as the result of the run method
  91. return Observable.error(ex);
  92. }
  93. }
  94. });
  95. }
  96. }

六、AbstractCommand#getExecutionObservable

  1. private Observable<R> getUserExecutionObservable(final AbstractCommand<R> _cmd) {
  2. Observable<R> userObservable;
  3. try {
  4. userObservable = getExecutionObservable();
  5. } catch (Throwable ex) {
  6. // the run() method is a user provided implementation so can throw instead of using Observable.onError
  7. // so we catch it here and turn it into Observable.error
  8. userObservable = Observable.error(ex);
  9. }
  10. return userObservable
  11. .lift(new ExecutionHookApplication(_cmd))
  12. .lift(new DeprecatedOnRunHookApplication(_cmd));
  13. }

在 AbstractCommand#getUserExecutionObservable 方法里会调用 HystrixCommand#getExecutionObservable 方法,HystrixCommand#getExecutionObservable方法代码如下:

  1. @Override
  2. final protected Observable<R> getExecutionObservable() {
  3. return Observable.defer(new Func0<Observable<R>>() {
  4. @Override
  5. public Observable<R> call() {
  6. try {
  7. // 执行被包装到 HystrixCommand 的远程调用逻辑中
  8. return Observable.just(run());
  9. } catch (Throwable ex) {
  10. return Observable.error(ex);
  11. }
  12. }
  13. }).doOnSubscribe(new Action0() {
  14. @Override
  15. public void call() {
  16. // Save thread on which we get subscribed so that we can interrupt it later if needed
  17. executionThread.set(Thread.currentThread());
  18. }
  19. });
  20. }

在上面的方法中,run方法也会被延迟到子类中实现,在高级应用中将尝试直接继承HystrixCommand和HystrixObservableCommand来构建对应的HystrixCommand,在HystrixCommand的默认实现GenericCommand中, run方法是通过创建HystrixCommand传入的CommandActions提供具体的实现。CommandActions持有commandAction和fallbackAction分别对应HystrixCommand中的远程调用和失败回滚方法。

七、同步、异步执行命令

在了解了HystrixObservable中的两个关键方法在AbstractCommand中的实现后,接下来就来简单看看HystrixCommand中execute同步执行命令和queue异步执行命令的相关实现,代码如下:

1.com.netflix.hystrix.HystrixCommand#execute

execute方法通过queue方法获取到Future,使用queue().get()方法获取到命令的执行结果,它将一直阻塞线程知道与执行结果返回。

  1. public R execute() {
  2. try {
  3. return queue().get();
  4. } catch (Exception e) {
  5. throw Exceptions.sneakyThrow(decomposeException(e));
  6. }
  7. }

2.com.netflix.hystrix.HystrixCommand#queue

queue方法中将 AbstractCommand#toObservable 获取到的Observable通过toBlocking()方法转化为具备阻塞功能的Blocking Observable,再通过toFuture()方法获取到能够执行的run抽象方法Future,最后通过Futere的到正在异步执行的命令执行结果。

  1. public Future<R> queue() {
  2. final Future<R> delegate = toObservable().toBlocking().toFuture();
  3. final Future<R> f = new Future<R>() {
  4. @Override
  5. public boolean cancel(boolean mayInterruptIfRunning) {
  6. if (delegate.isCancelled()) {
  7. return false;
  8. }
  9. if (HystrixCommand.this.getProperties().executionIsolationThreadInterruptOnFutureCancel().get()) {
  10. interruptOnFutureCancel.compareAndSet(false, mayInterruptIfRunning);
  11. }
  12. final boolean res = delegate.cancel(interruptOnFutureCancel.get());
  13. if (!isExecutionComplete() && interruptOnFutureCancel.get()) {
  14. final Thread t = executionThread.get();
  15. if (t != null && !t.equals(Thread.currentThread())) {
  16. t.interrupt();
  17. }
  18. }
  19. return res;
  20. }
  21. @Override
  22. public boolean isCancelled() {
  23. return delegate.isCancelled();
  24. }
  25. @Override
  26. public boolean isDone() {
  27. return delegate.isDone();
  28. }
  29. @Override
  30. public R get() throws InterruptedException, ExecutionException {
  31. return delegate.get();
  32. }
  33. @Override
  34. public R get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
  35. return delegate.get(timeout, unit);
  36. }
  37. };
  38. /* special handling of error states that throw immediately */
  39. if (f.isDone()) {
  40. try {
  41. f.get();
  42. return f;
  43. } catch (Exception e) {
  44. Throwable t = decomposeException(e);
  45. if (t instanceof HystrixBadRequestException) {
  46. return f;
  47. } else if (t instanceof HystrixRuntimeException) {
  48. HystrixRuntimeException hre = (HystrixRuntimeException) t;
  49. switch (hre.getFailureType()) {
  50. case COMMAND_EXCEPTION:
  51. case TIMEOUT:
  52. // we don't throw these types from queue() only from queue().get() as they are execution errors
  53. return f;
  54. default:
  55. // these are errors we throw from queue() as they as rejection type errors
  56. throw hre;
  57. }
  58. } else {
  59. throw Exceptions.sneakyThrow(t);
  60. }
  61. }
  62. }
  63. return f;
  64. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/978674
推荐阅读
  

闽ICP备14008679号