Hystrix是个什么玩意儿

ゞ 浴缸里的玫瑰 2023-07-04 15:58 34阅读 0赞

format_png

  1. 什么是Hystrix

format_png 1

Hystrix是Netflix的一个开源框架,地址如下:https://github.com/Netflix/Hystrix

中文名为“豪猪”,即平时很温顺,在感受到危险的时候,用刺保护自己;在危险过去后,还是一个温顺的肉球。

所以,整个框架的核心业务也就是这2点:

  1. 何时需要保护
  2. 如何保护

2. 何时需要保护

对于一个系统而言,它往往承担着2层角色,服务提供者与服务消费者。对于服务消费者而言最大的痛苦就是如何“明哲保身”,做过网关项目的同学肯定感同身受

format_png 2

上面是一个常见的系统依赖关系,底层的依赖往往很多,通信协议包括 socket、HTTP、Dubbo、WebService等等。当通信层发生网络抖动以及所依赖的系统发生业务响应异常时,我们业务本身所提供的服务能力也直接会受到影响。

这种效果传递下去就很有可能造成雪崩效应,即整个业务联调发生异常,比如业务整体超时,或者订单数据不一致。

那么核心问题就来了,如何检测业务处于异常状态?

成功率!成功率直接反映了业务的数据流转状态,是最直接的业务表现。

当然,也可以根据超时时间做判断,比如 Sentinel 的实现。其实这里概念上可以做一个转化,用时间做超时控制,超时=失败,这依然是一个成功率的概念。

3. 如何保护 

如同豪猪一样,“刺”就是他的保护工具,所有的攻击都会被刺无情的怼回去。

在 Hystrix 的实现中,这就出现了“熔断器”的概念,即当前的系统是否处于需要保护的状态。

当熔断器处于开启的状态时,所有的请求都不会真正的走之前的业务逻辑,而是直接返回一个约定的信息,即 FallBack。通过这种快速失败原则保护我们的系统。

但是,系统不应该永远处于“有刺”的状态,当危险过后需要恢复正常。

于是对熔断器的核心操作就是如下几个功能:

  1. 如果成功率过低,就打开熔断器,阻止正常业务
  2. 随着时间的流动,熔断器处于半打开状态,尝试性放入一笔请求

  熔断器的核心 API 如下图:

format_png 3

4. 限流、熔断、隔离、降级

这四个概念是我们谈起微服务会经常谈到的概念,这里我们讨论的是 Hystrix 的实现方式。

限流

  • 这里的限流与 Guava 的 RateLimiter 的限流差异比较大,一个是为了“保护自我”,一个是“保护下游”
  • 当对服务进行限流时,超过的流量将直接 Fallback,即熔断。而 RateLimiter 关心的其实是“流量整形”,将不规整流量在一定速度内规整

熔断

  • 当我的应用无法提供服务时,我要对上游请求熔断,避免上游把我压垮
  • 当我的下游依赖成功率过低时,我要对下游请求熔断,避免下游把我拖垮

降级

  • 降级与熔断紧密相关,熔断后业务如何表现,约定一个快速失败的 Fallback,即为服务降级

隔离

  • 业务之间不可互相影响,不同业务需要有独立的运行空间
  • 最彻底的,可以采用物理隔离,不同的机器部
  • 次之,采用进程隔离,一个机器多个 Tomcat
  • 次之,请求隔离
  • 由于 Hystrix 框架所属的层级为代码层,所以实现的是请求隔离,线程池或信号量

5. 源码分析

先上一个 Hystrix 的业务流程图

format_png 4

可以看到 Hystrix 的请求都要经过 HystrixCommand 的包装,其核心逻辑在 AbstractComman.java 类中。

下面的源码是基于 RxJava 的,看之前最好先了解下 RxJava 的常见用法与逻辑,否则看起来会很迷惑。

简单的说,RxJava 就是基于回调的函数式编程。通俗的说,就等同于策略模式的匿名内部类实现。

5.1 熔断器

首先看信号量是如何影响我们请求的:

  1. private Observable<R> applyHystrixSemantics(final AbstractCommand<R> _cmd) {
  2. // 自定义扩展
  3. executionHook.onStart(_cmd);
  4. //判断熔断器是否允许请求过来
  5. if (circuitBreaker.attemptExecution()) {
  6.        //获得分组信号量,如果没有采用信号量分组,返回默认通过的信号量实现
  7. final TryableSemaphore executionSemaphore = getExecutionSemaphore();
  8. final AtomicBoolean semaphoreHasBeenReleased = new AtomicBoolean(false);
  9.        //调用终止的回调函数
  10. final Action0 singleSemaphoreRelease = new Action0() {
  11. @Override
  12. public void call() {
  13. if (semaphoreHasBeenReleased.compareAndSet(false, true)) {
  14. executionSemaphore.release();
  15. }
  16. }
  17. };
  18.        //调用异常的回调函数
  19. final Action1<Throwable> markExceptionThrown = new Action1<Throwable>() {
  20. @Override
  21. public void call(Throwable t) {
  22. eventNotifier.markEvent(HystrixEventType.EXCEPTION_THROWN, commandKey);
  23. }
  24. };
  25.        //根据信号量尝试竞争信号量
  26. if (executionSemaphore.tryAcquire()) {
  27. try {
  28. //竞争成功,注册执行参数
  29. executionResult = executionResult.setInvocationStartTime(System.currentTimeMillis());
  30. return executeCommandAndObserve(_cmd)
  31. .doOnError(markExceptionThrown)
  32. .doOnTerminate(singleSemaphoreRelease)
  33. .doOnUnsubscribe(singleSemaphoreRelease);
  34. } catch (RuntimeException e) {
  35. return Observable.error(e);
  36. }
  37. } else {
  38.           //竞争失败,进入fallback
  39. return handleSemaphoreRejectionViaFallback();
  40. }
  41. } else {
  42.         //熔断器已打开,进入fallback
  43. return handleShortCircuitViaFallback();
  44. }
  45. }

什么时候熔断器可以放请求进来:

  1. @Override
  2. public boolean attemptExecution() {
  3.        //动态属性判断,熔断器是否强制开着,如果强制开着,就不允许请求
  4. if (properties.circuitBreakerForceOpen().get()) {
  5. return false;
  6. }
  7.        //如果强制关闭,就允许请求
  8. if (properties.circuitBreakerForceClosed().get()) {
  9. return true;
  10. }
  11.        //如果当前是关闭,就允许请求
  12. if (circuitOpened.get() == -1) {
  13. return true;
  14. } else {
  15.           //如果当前开着,就看是否已经过了"滑动窗口",过了就可以请求,不过就不可以
  16. if (isAfterSleepWindow()) {
  17. //only the first request after sleep window should execute
  18. //if the executing command succeeds, the status will transition to CLOSED
  19. //if the executing command fails, the status will transition to OPEN
  20. //if the executing command gets unsubscribed, the status will transition to OPEN
  21.             //这里使用CAS的方式,只有一个请求能过来,即"半关闭"状态
  22. if (status.compareAndSet(Status.OPEN, Status.HALF_OPEN)) {
  23. return true;
  24. } else {
  25. return false;
  26. }
  27. } else {
  28. return false;
  29. }
  30. }
  31. }
  32. }

这里有个重要概念就是”滑动窗口”:

  1. private boolean isAfterSleepWindow() {
  2. final long circuitOpenTime = circuitOpened.get();
  3. final long currentTime = System.currentTimeMillis();
  4. final long sleepWindowTime = properties.circuitBreakerSleepWindowInMilliseconds().get();
  5.        //滑动窗口的判断就是看看熔断器打开的时间与现在相比是否超过了配置的滑动窗口
  6. return currentTime > circuitOpenTime + sleepWindowTime;
  7. }

5.2 隔离

如果将业务请求进行隔离?

  1. private Observable<R> executeCommandWithSpecifiedIsolation(final AbstractCommand<R> _cmd) {
  2.      //判断隔离策略是什么,是线程池隔离还是信号量隔离    
  3. if (properties.executionIsolationStrategy().get() == ExecutionIsolationStrategy.THREAD) {
  4. // mark that we are executing in a thread (even if we end up being rejected we still were a THREAD execution and not SEMAPHORE)
  5.        //线程池隔离的运行逻辑如下
  6. return Observable.defer(new Func0<Observable<R>>() {
  7. @Override
  8. public Observable<R> call() {
  9. executionResult = executionResult.setExecutionOccurred();
  10. if (!commandState.compareAndSet(CommandState.OBSERVABLE_CHAIN_CREATED, CommandState.USER_CODE_EXECUTED)) {
  11. return Observable.error(new IllegalStateException("execution attempted while in state : " + commandState.get().name()));
  12. }
  13.             //按照配置生成监控数据
  14. metrics.markCommandStart(commandKey, threadPoolKey, ExecutionIsolationStrategy.THREAD);
  15. if (isCommandTimedOut.get() == TimedOutStatus.TIMED_OUT) {
  16. // the command timed out in the wrapping thread so we will return immediately
  17. // and not increment any of the counters below or other such logic
  18. return Observable.error(new RuntimeException("timed out before executing run()"));
  19. }
  20. if (threadState.compareAndSet(ThreadState.NOT_USING_THREAD, ThreadState.STARTED)) {
  21. //we have not been unsubscribed, so should proceed
  22. HystrixCounters.incrementGlobalConcurrentThreads();
  23. threadPool.markThreadExecution();
  24. // store the command that is being run
  25. endCurrentThreadExecutingCommand = Hystrix.startCurrentThreadExecutingCommand(getCommandKey());
  26. executionResult = executionResult.setExecutedInThread();
  27. /**
  28. * If any of these hooks throw an exception, then it appears as if the actual execution threw an error
  29. */
  30. try {
  31.                  //执行扩展点逻辑
  32. executionHook.onThreadStart(_cmd);
  33. executionHook.onRunStart(_cmd);
  34. executionHook.onExecutionStart(_cmd);
  35. return getUserExecutionObservable(_cmd);
  36. } catch (Throwable ex) {
  37. return Observable.error(ex);
  38. }
  39. } else {
  40. //command has already been unsubscribed, so return immediately
  41. return Observable.empty();
  42. }
  43. }
  44.         //注册各种场景的回调函数
  45. }).doOnTerminate(new Action0() {
  46. @Override
  47. public void call() {
  48. if (threadState.compareAndSet(ThreadState.STARTED, ThreadState.TERMINAL)) {
  49. handleThreadEnd(_cmd);
  50. }
  51. if (threadState.compareAndSet(ThreadState.NOT_USING_THREAD, ThreadState.TERMINAL)) {
  52. //if it was never started and received terminal, then no need to clean up (I don't think this is possible)
  53. }
  54. //if it was unsubscribed, then other cleanup handled it
  55. }
  56. }).doOnUnsubscribe(new Action0() {
  57. @Override
  58. public void call() {
  59. if (threadState.compareAndSet(ThreadState.STARTED, ThreadState.UNSUBSCRIBED)) {
  60. handleThreadEnd(_cmd);
  61. }
  62. if (threadState.compareAndSet(ThreadState.NOT_USING_THREAD, ThreadState.UNSUBSCRIBED)) {
  63. //if it was never started and was cancelled, then no need to clean up
  64. }
  65. //if it was terminal, then other cleanup handled it
  66. }
  67.         //将逻辑放在线程池的调度器上执行,即将上述逻辑放入线程池中
  68. }).subscribeOn(threadPool.getScheduler(new Func0<Boolean>() {
  69. @Override
  70. public Boolean call() {
  71. return properties.executionIsolationThreadInterruptOnTimeout().get() && _cmd.isCommandTimedOut.get() == TimedOutStatus.TIMED_OUT;
  72. }
  73. }));
  74. } else {
  75.         //走到这里就是信号量隔离,在当前线程中执行,没有调度器
  76. return Observable.defer(new Func0<Observable<R>>() {
  77. @Override
  78. public Observable<R> call() {
  79. executionResult = executionResult.setExecutionOccurred();
  80. if (!commandState.compareAndSet(CommandState.OBSERVABLE_CHAIN_CREATED, CommandState.USER_CODE_EXECUTED)) {
  81. return Observable.error(new IllegalStateException("execution attempted while in state : " + commandState.get().name()));
  82. }
  83. metrics.markCommandStart(commandKey, threadPoolKey, ExecutionIsolationStrategy.SEMAPHORE);
  84. // semaphore isolated
  85. // store the command that is being run
  86. endCurrentThreadExecutingCommand = Hystrix.startCurrentThreadExecutingCommand(getCommandKey());
  87. try {
  88. executionHook.onRunStart(_cmd);
  89. executionHook.onExecutionStart(_cmd);
  90. return getUserExecutionObservable(_cmd); //the getUserExecutionObservable method already wraps sync exceptions, so this shouldn't throw
  91. } catch (Throwable ex) {
  92. //If the above hooks throw, then use that as the result of the run method
  93. return Observable.error(ex);
  94. }
  95. }
  96. });
  97. }
  98. }

5.3 核心运行流程

  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.markEvent(HystrixEventType.SUCCESS, commandKey);
  14. executionResult = executionResult.addEvent((int) latency, HystrixEventType.SUCCESS);
  15. eventNotifier.markCommandExecution(getCommandKey(), properties.executionIsolationStrategy().get(), (int) latency, executionResult.getOrderedList());
  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.markEvent(HystrixEventType.SUCCESS, commandKey);
  27. executionResult = executionResult.addEvent((int) latency, HystrixEventType.SUCCESS);
  28. eventNotifier.markCommandExecution(getCommandKey(), properties.executionIsolationStrategy().get(), (int) latency, executionResult.getOrderedList());
  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. circuitBreaker.markNonSuccess();
  38. Exception e = getExceptionFromThrowable(t);
  39. executionResult = executionResult.setExecutionException(e);
  40.           //各种回调进行各种fallback
  41. if (e instanceof RejectedExecutionException) {
  42. return handleThreadPoolRejectionViaFallback(e);
  43. } else if (t instanceof HystrixTimeoutException) {
  44. return handleTimeoutViaFallback();
  45. } else if (t instanceof HystrixBadRequestException) {
  46. return handleBadRequestByEmittingError(e);
  47. } else {
  48. /*
  49. * Treat HystrixBadRequestException from ExecutionHook like a plain HystrixBadRequestException.
  50. */
  51. if (e instanceof HystrixBadRequestException) {
  52. eventNotifier.markEvent(HystrixEventType.BAD_REQUEST, commandKey);
  53. return Observable.error(e);
  54. }
  55. return handleFailureViaFallback(e);
  56. }
  57. }
  58. };
  59. final Action1<Notification<? super R>> setRequestContext = new Action1<Notification<? super R>>() {
  60. @Override
  61. public void call(Notification<? super R> rNotification) {
  62. setRequestContextIfNeeded(currentRequestContext);
  63. }
  64. };
  65. Observable<R> execution;
  66. if (properties.executionTimeoutEnabled().get()) {
  67. execution = executeCommandWithSpecifiedIsolation(_cmd)
  68. .lift(new HystrixObservableTimeoutOperator<R>(_cmd));
  69. } else {
  70. execution = executeCommandWithSpecifiedIsolation(_cmd);
  71. }
  72.      //注册各种回调函数
  73. return execution.doOnNext(markEmits)
  74. .doOnCompleted(markOnCompleted)
  75. .onErrorResumeNext(handleFallback)
  76. .doOnEach(setRequestContext);
  77. }

6. 小结

  • Hystrix 是基于单机应用的熔断限流框架
  • 根据熔断器的滑动窗口判断当前请求是否可以执行
  • 线程竞争实现“半关闭”状态,拿一个请求试试是否可以关闭熔断器
  • 线程池隔离将请求丢到线程池中运行,限流依靠线程池拒绝策略
  • 信号量隔离在当前线程中运行,限流依靠并发请求数
  • 当信号量竞争失败/线程池队列满,就进入限流模式,执行 Fallback
  • 当熔断器开启,就熔断请求,执行 Fallback 
  • 整个框架采用的 RxJava 的编程模式,回调函数满天飞 

format_png 5

  • 微服务架构下的核心话题 (一):微服务架构下各类项目的顺势崛起
  • 微服务架构下的核心话题 (二):微服务架构的设计原则和核心话题
  • 微服务架构下的核心话题 (三):微服务架构的技术选型
  • 【JVM系列】1.Java虚拟机内存模型
  • 以后要是再写for循环,我就捶自己
  • 什么?你项目还在用Date表示时间?

format_png 6

喜欢就点个”在看”呗,留言、转发朋友圈

发表评论

表情:
评论列表 (有 0 条评论,34人围观)

还没有评论,来说两句吧...

相关阅读