当前位置:   article > 正文

Hystrix之源码剖析_hystrixruntimeexception: failed while executing

hystrixruntimeexception: failed while executing

附:SpringCloud之系列汇总跳转地址

一、认识Hystrix

Hystrix是Netflix开源的一款容错框架,包含常用的容错方法:线程池隔离、信号量隔离、熔断、降级回退。在高并发访问下,系统所依赖的服务的稳定性对系统的影响非常大,依赖有很多不可控的因素,比如网络连接变慢,资源突然繁忙,暂时不可用,服务脱机等。我们要构建稳定、可靠的分布式系统,就必须要有这样一套容错方法。 本文将逐一分析线程池隔离、信号量隔离、熔断、降级回退这四种技术的原理与实践。

二、线程隔离

2.1为什么要做线程隔离

比如我们现在有3个业务调用分别是查询订单、查询商品、查询用户,且这三个业务请求都是依赖第三方服务-订单服务、商品服务、用户服务。三个服务均是通过RPC调用。当查询订单服务,假如线程阻塞了,这个时候后续有大量的查询订单请求过来,那么容器中的线程数量则会持续增加直致CPU资源耗尽到100%,整个服务对外不可用,集群环境下就是雪崩。如下图

 

2.2、线程隔离-线程池

2.2.1、Hystrix是如何通过线程池实现线程隔离的

Hystrix通过命令模式,将每个类型的业务请求封装成对应的命令请求,比如查询订单->订单Command,查询商品->商品Command,查询用户->用户Command。每个类型的Command对应一个线程池。创建好的线程池是被放入到ConcurrentHashMap中,比如查询订单:

  1. final static ConcurrentHashMap<String, HystrixThreadPool> threadPools = new ConcurrentHashMap<String, HystrixThreadPool>();
  2. threadPools.put(“hystrix-order”, new HystrixThreadPoolDefault(threadPoolKey, propertiesBuilder));

 当第二次查询订单请求过来的时候,则可以直接从Map中获取该线程池。具体流程如下图:

创建线程池中的线程的方法,查看源代码如下:

  1. public ThreadPoolExecutor getThreadPool(final HystrixThreadPoolKey threadPoolKey, HystrixProperty<Integer> corePoolSize, HystrixProperty<Integer> maximumPoolSize, HystrixProperty<Integer> keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
  2. ThreadFactory threadFactory = null;
  3. if (!PlatformSpecific.isAppEngineStandardEnvironment()) {
  4. threadFactory = new ThreadFactory() {
  5. protected final AtomicInteger threadNumber = new AtomicInteger(0);
  6. @Override
  7. public Thread newThread(Runnable r) {
  8. Thread thread = new Thread(r, "hystrix-" + threadPoolKey.name() + "-" + threadNumber.incrementAndGet());
  9. thread.setDaemon(true);
  10. return thread;
  11. }
  12. };
  13. } else {
  14. threadFactory = PlatformSpecific.getAppEngineThreadFactory();
  15. }
  16. final int dynamicCoreSize = corePoolSize.get();
  17. final int dynamicMaximumSize = maximumPoolSize.get();
  18. if (dynamicCoreSize > dynamicMaximumSize) {
  19. logger.error("Hystrix ThreadPool configuration at startup for : " + threadPoolKey.name() + " is trying to set coreSize = " +
  20. dynamicCoreSize + " and maximumSize = " + dynamicMaximumSize + ". Maximum size will be set to " +
  21. dynamicCoreSize + ", the coreSize value, since it must be equal to or greater than the coreSize value");
  22. return new ThreadPoolExecutor(dynamicCoreSize, dynamicCoreSize, keepAliveTime.get(), unit, workQueue, threadFactory);
  23. } else {
  24. return new ThreadPoolExecutor(dynamicCoreSize, dynamicMaximumSize, keepAliveTime.get(), unit, workQueue, threadFactory);
  25. }
  26. }

执行Command的方式一共四种,直接看官方文档(github.com/Netflix/Hys…),具体区别如下:

  • execute():以同步堵塞方式执行run()。调用execute()后,hystrix先创建一个新线程运行run(),接着调用程序要在execute()调用处一直堵塞着,直到run()运行完成。

  • queue():以异步非堵塞方式执行run()。调用queue()就直接返回一个Future对象,同时hystrix创建一个新线程运行run(),调用程序通过Future.get()拿到run()的返回结果,而Future.get()是堵塞执行的。

  • observe():事件注册前执行run()/construct()。第一步是事件注册前,先调用observe()自动触发执行run()/construct()(如果继承的是HystrixCommand,hystrix将创建新线程非堵塞执行run();如果继承的是HystrixObservableCommand,将以调用程序线程堵塞执行construct()),第二步是从observe()返回后调用程序调用subscribe()完成事件注册,如果run()/construct()执行成功则触发onNext()和onCompleted(),如果执行异常则触发onError()。

  • toObservable():事件注册后执行run()/construct()。第一步是事件注册前,调用toObservable()就直接返回一个Observable<String>对象,第二步调用subscribe()完成事件注册后自动触发执行run()/construct()(如果继承的是HystrixCommand,hystrix将创建新线程非堵塞执行run(),调用程序不必等待run();如果继承的是HystrixObservableCommand,将以调用程序线程堵塞执行construct(),调用程序等待construct()执行完才能继续往下走),如果run()/construct()执行成功则触发onNext()和onCompleted(),如果执行异常则触发onError()
    注:
    execute()和queue()是HystrixCommand中的方法,observe()和toObservable()是HystrixObservableCommand 中的方法。从底层实现来讲,HystrixCommand其实也是利用Observable实现的(如果我们看Hystrix的源码的话,可以发现里面大量使用了RxJava),虽然HystrixCommand只返回单个的结果,但HystrixCommand的queue方法实际上是调用了toObservable().toBlocking().toFuture(),而execute方法实际上是调用了queue().get()。

2.2.2、如何应用到实际代码中

  1. package myHystrix.threadpool;
  2. import com.netflix.hystrix.*;
  3. import org.junit.Test;
  4. import java.util.List;
  5. import java.util.concurrent.Future;
  6. /**
  7. * Created by wangxindong on 2017/8/4.
  8. */
  9. public class GetOrderCommand extends HystrixCommand<List> {
  10. OrderService orderService;
  11. public GetOrderCommand(String name){
  12. super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ThreadPoolTestGroup"))
  13. .andCommandKey(HystrixCommandKey.Factory.asKey("testCommandKey"))
  14. .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey(name))
  15. .andCommandPropertiesDefaults(
  16. HystrixCommandProperties.Setter()
  17. .withExecutionTimeoutInMilliseconds(5000)
  18. )
  19. .andThreadPoolPropertiesDefaults(
  20. HystrixThreadPoolProperties.Setter()
  21. .withMaxQueueSize(10) //配置队列大小
  22. .withCoreSize(2) // 配置线程池里的线程数
  23. )
  24. );
  25. }
  26. @Override
  27. protected List run() throws Exception {
  28. return orderService.getOrderList();
  29. }
  30. public static class UnitTest {
  31. @Test
  32. public void testGetOrder(){
  33. // new GetOrderCommand("hystrix-order").execute();
  34. Future<List> future =new GetOrderCommand("hystrix-order").queue();
  35. }
  36. }
  37. }

2.2.3、线程隔离-线程池小结

执行依赖代码的线程与请求线程(比如Tomcat线程)分离,请求线程可以自由控制离开的时间,这也是我们通常说的异步编程,Hystrix是结合RxJava来实现的异步编程。通过设置线程池大小来控制并发访问量,当线程饱和的时候可以拒绝服务,防止依赖问题扩散。

线程池隔离的优点:
[1]:应用程序会被完全保护起来,即使依赖的一个服务的线程池满了,也不会影响到应用程序的其他部分。
[2]:我们给应用程序引入一个新的风险较低的客户端lib的时候,如果发生问题,也是在本lib中,并不会影响到其他内容,因此我们可以大胆的引入新lib库。
[3]:当依赖的一个失败的服务恢复正常时,应用程序会立即恢复正常的性能。
[4]:如果我们的应用程序一些参数配置错误了,线程池的运行状况将会很快显示出来,比如延迟、超时、拒绝等。同时可以通过动态属性实时执行来处理纠正错误的参数配置。
[5]:如果服务的性能有变化,从而需要调整,比如增加或者减少超时时间,更改重试次数,就可以通过线程池指标动态属性修改,而且不会影响到其他调用请求。
[6]:除了隔离优势外,hystrix拥有专门的线程池可提供内置的并发功能,使得可以在同步调用之上构建异步的外观模式,这样就可以很方便的做异步编程(Hystrix引入了Rxjava异步框架)。

尽管线程池提供了线程隔离,我们的客户端底层代码也必须要有超时设置,不能无限制的阻塞以致线程池一直饱和。

线程池隔离的缺点:
[1]:线程池的主要缺点就是它增加了计算的开销,每个业务请求(被包装成命令)在执行的时候,会涉及到请求排队,调度和上下文切换。不过Netflix公司内部认为线程隔离开销足够小,不会产生重大的成本或性能的影响。

The Netflix API processes 10+ billion Hystrix Command executions per day using thread isolation. Each API instance has 40+ thread-pools with 5–20 threads in each (most are set to 10). Netflix API每天使用线程隔离处理10亿次Hystrix Command执行。 每个API实例都有40多个线程池,每个线程池中有5-20个线程(大多数设置为10个)。

对于不依赖网络访问的服务,比如只依赖内存缓存这种情况下,就不适合用线程池隔离技术,而是采用信号量隔离。

threadPoolKey用于从线程池缓存中获取线程池 和 初始化创建线程池,由于默认以groupKey即类名为threadPoolKey,那么默认所有在一个类中的HystrixCommand共用一个线程池。一般来说我们会为每一个微服务的Hystrix调用创建一个Service类,可以认为一个微服务对应一个线程池

2.3、线程隔离-信号量。

2.3.1、线程池和信号量的区别

上面谈到了线程池的缺点,当我们依赖的服务是极低延迟的,比如访问内存缓存,就没有必要使用线程池的方式,那样的话开销得不偿失,而是推荐使用信号量这种方式。下面这张图说明了线程池隔离和信号量隔离的主要区别:线程池方式下业务请求线程和执行依赖的服务的线程不是同一个线程;信号量方式下业务请求线程和执行依赖服务的线程是同一个线程

2.3.2、如何使用信号量来隔离线程

将属性execution.isolation.strategy设置为SEMAPHORE ,象这样 ExecutionIsolationStrategy.SEMAPHORE,则Hystrix使用信号量而不是默认的线程池来做隔离。

  1. public class CommandUsingSemaphoreIsolation extends HystrixCommand<String> {
  2. private final int id;
  3. public CommandUsingSemaphoreIsolation(int id) {
  4. super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"))
  5. // since we're doing work in the run() method that doesn't involve network traffic
  6. // and executes very fast with low risk we choose SEMAPHORE isolation
  7. .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
  8. .withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE)));
  9. this.id = id;
  10. }
  11. @Override
  12. protected String run() {
  13. // a real implementation would retrieve data from in memory data structure
  14. // or some other similar non-network involved work
  15. return "ValueFromHashMap_" + id;
  16. }
  17. }

2.3.4、线程隔离-信号量小结

信号量隔离的方式是限制了总的并发数,每一次请求过来,请求线程和调用依赖服务的线程是同一个线程,那么如果不涉及远程RPC调用(没有网络开销)则使用信号量来隔离,更为轻量,开销更小。

线程池技术,适合绝大多数场景,比如说我们对依赖服务的网络请求的调用和访问、需要对调用的 timeout 进行控制(捕捉 timeout 超时异常)。

信号量技术,适合说你的访问不是对外部依赖的访问,而是对内部的一些比较复杂的业务逻辑的访问,并且系统内部的代码,其实不涉及任何的网络请求,那么只要做信号量的普通限流就可以了,因为不需要去捕获 timeout 类似的问题。

三、熔断

3.1、熔断器(Circuit Breaker)介绍

熔断器,现实生活中有一个很好的类比,就是家庭电路中都会安装一个保险盒,当电流过大的时候保险盒里面的保险丝会自动断掉,来保护家里的各种电器及电路。Hystrix中的熔断器(Circuit Breaker)也是起到这样的作用,Hystrix在运行过程中会向每个commandKey对应的熔断器报告成功、失败、超时和拒绝的状态,熔断器维护计算统计的数据,根据这些统计的信息来确定熔断器是否打开。如果打开,后续的请求都会被截断。然后会隔一段时间默认是5s,尝试半开,放入一部分流量请求进来,相当于对依赖服务进行一次健康检查,如果恢复,熔断器关闭,随后完全恢复调用。如下图:

 说明,上面说的commandKey,就是在初始化的时候设置的andCommandKey(HystrixCommandKey.Factory.asKey("testCommandKey"))

再来看下熔断器在整个Hystrix流程图中的位置,从步骤4开始,如下图:

Hystrix会检查Circuit Breaker的状态。如果Circuit Breaker的状态为开启状态,Hystrix将不会执行对应指令,而是直接进入失败处理状态(图中8 Fallback)。如果Circuit Breaker的状态为关闭状态,Hystrix会继续进行线程池、任务队列、信号量的检查(图中5)

3.2、如何使用熔断器(Circuit Breaker)

由于Hystrix是一个容错框架,因此我们在使用的时候,要达到熔断的目的只需配置一些参数就可以了。但我们要达到真正的效果,就必须要了解这些参数。Circuit Breaker一共包括如下6个参数。
1、circuitBreaker.enabled
是否启用熔断器,默认是TURE。
2、circuitBreaker.forceOpen
熔断器强制打开,始终保持打开状态。默认值FLASE。
3、circuitBreaker.forceClosed
熔断器强制关闭,始终保持关闭状态。默认值FLASE。
4、circuitBreaker.errorThresholdPercentage
设定错误百分比,默认值50%,例如一段时间(10s)内有100个请求,其中有55个超时或者异常返回了,那么这段时间内的错误百分比是55%,大于了默认值50%,这种情况下触发熔断器-打开。
5、circuitBreaker.requestVolumeThreshold
默认值20.意思是至少有20个请求才进行errorThresholdPercentage错误百分比计算。比如一段时间(10s)内有19个请求全部失败了。错误百分比是100%,但熔断器不会打开,因为requestVolumeThreshold的值是20. 这个参数非常重要,熔断器是否打开首先要满足这个条件,源代码如下

  1. // check if we are past the statisticalWindowVolumeThreshold
  2. if (health.getTotalRequests() < properties.circuitBreakerRequestVolumeThreshold().get()) {
  3. // we are not past the minimum volume threshold for the statisticalWindow so we'll return false immediately and not calculate anything
  4. return false;
  5. }
  6. if (health.getErrorPercentage() < properties.circuitBreakerErrorThresholdPercentage().get()) {
  7. return false;
  8. }

6、circuitBreaker.sleepWindowInMilliseconds
半开试探休眠时间,默认值5000ms。当熔断器开启一段时间之后比如5000ms,会尝试放过去一部分流量进行试探,确定依赖服务是否恢复。

测试代码(模拟10次调用,错误百分比为5%的情况下,打开熔断器开关。):

  1. package myHystrix.threadpool;
  2. import com.netflix.hystrix.*;
  3. import org.junit.Test;
  4. import java.util.Random;
  5. /**
  6. * Created by wangxindong on 2017/8/15.
  7. */
  8. public class GetOrderCircuitBreakerCommand extends HystrixCommand<String> {
  9. public GetOrderCircuitBreakerCommand(String name){
  10. super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ThreadPoolTestGroup"))
  11. .andCommandKey(HystrixCommandKey.Factory.asKey("testCommandKey"))
  12. .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey(name))
  13. .andCommandPropertiesDefaults(
  14. HystrixCommandProperties.Setter()
  15. .withCircuitBreakerEnabled(true)//默认是true,本例中为了展现该参数
  16. .withCircuitBreakerForceOpen(false)//默认是false,本例中为了展现该参数
  17. .withCircuitBreakerForceClosed(false)//默认是false,本例中为了展现该参数
  18. .withCircuitBreakerErrorThresholdPercentage(5)//(1)错误百分比超过5%
  19. .withCircuitBreakerRequestVolumeThreshold(10)//(2)10s以内调用次数10次,同时满足(1)(2)熔断器打开
  20. .withCircuitBreakerSleepWindowInMilliseconds(5000)//5s之后,熔断器会尝试半开(关闭),重新放进来请求
  21. // .withExecutionTimeoutInMilliseconds(1000)
  22. )
  23. .andThreadPoolPropertiesDefaults(
  24. HystrixThreadPoolProperties.Setter()
  25. .withMaxQueueSize(10) //配置队列大小
  26. .withCoreSize(2) // 配置线程池里的线程数
  27. )
  28. );
  29. }
  30. @Override
  31. protected String run() throws Exception {
  32. Random rand = new Random();
  33. //模拟错误百分比(方式比较粗鲁但可以证明问题)
  34. if(1==rand.nextInt(2)){
  35. // System.out.println("make exception");
  36. throw new Exception("make exception");
  37. }
  38. return "running: ";
  39. }
  40. @Override
  41. protected String getFallback() {
  42. // System.out.println("FAILBACK");
  43. return "fallback: ";
  44. }
  45. public static class UnitTest{
  46. @Test
  47. public void testCircuitBreaker() throws Exception{
  48. for(int i=0;i<25;i++){
  49. Thread.sleep(500);
  50. HystrixCommand<String> command = new GetOrderCircuitBreakerCommand("testCircuitBreaker");
  51. String result = command.execute();
  52. //本例子中从第11次,熔断器开始打开
  53. System.out.println("call times:"+(i+1)+" result:"+result +" isCircuitBreakerOpen: "+command.isCircuitBreakerOpen());
  54. //本例子中5s以后,熔断器尝试关闭,放开新的请求进来
  55. }
  56. }
  57. }
  58. }

测试结果:

call times:1 result:fallback: isCircuitBreakerOpen: false
call times:2 result:running: isCircuitBreakerOpen: false
call times:3 result:running: isCircuitBreakerOpen: false
call times:4 result:fallback: isCircuitBreakerOpen: false
call times:5 result:running: isCircuitBreakerOpen: false
call times:6 result:fallback: isCircuitBreakerOpen: false
call times:7 result:fallback: isCircuitBreakerOpen: false
call times:8 result:fallback: isCircuitBreakerOpen: false
call times:9 result:fallback: isCircuitBreakerOpen: false
call times:10 result:fallback: isCircuitBreakerOpen: false
熔断器打开
call times:11 result:fallback: isCircuitBreakerOpen: true
call times:12 result:fallback: isCircuitBreakerOpen: true
call times:13 result:fallback: isCircuitBreakerOpen: true
call times:14 result:fallback: isCircuitBreakerOpen: true
call times:15 result:fallback: isCircuitBreakerOpen: true
call times:16 result:fallback: isCircuitBreakerOpen: true
call times:17 result:fallback: isCircuitBreakerOpen: true
call times:18 result:fallback: isCircuitBreakerOpen: true
call times:19 result:fallback: isCircuitBreakerOpen: true
call times:20 result:fallback: isCircuitBreakerOpen: true
5s后熔断器关闭
call times:21 result:running: isCircuitBreakerOpen: false
call times:22 result:running: isCircuitBreakerOpen: false
call times:23 result:fallback: isCircuitBreakerOpen: false
call times:24 result:running: isCircuitBreakerOpen: false
call times:25 result:running: isCircuitBreakerOpen: false

3.3、熔断器(Circuit Breaker)源代码HystrixCircuitBreaker.java分析

 Factory 是一个工厂类,提供HystrixCircuitBreaker实例

  1. public static class Factory {
  2. //用一个ConcurrentHashMap来保存HystrixCircuitBreaker对象
  3. private static ConcurrentHashMap<String, HystrixCircuitBreaker> circuitBreakersByCommand = new ConcurrentHashMap<String, HystrixCircuitBreaker>();
  4. //Hystrix首先会检查ConcurrentHashMap中有没有对应的缓存的断路器,如果有的话直接返回。如果没有的话就会新创建一个HystrixCircuitBreaker实例,将其添加到缓存中并且返回
  5. public static HystrixCircuitBreaker getInstance(HystrixCommandKey key, HystrixCommandGroupKey group, HystrixCommandProperties properties, HystrixCommandMetrics metrics) {
  6. HystrixCircuitBreaker previouslyCached = circuitBreakersByCommand.get(key.name());
  7. if (previouslyCached != null) {
  8. return previouslyCached;
  9. }
  10. HystrixCircuitBreaker cbForCommand = circuitBreakersByCommand.putIfAbsent(key.name(), new HystrixCircuitBreakerImpl(key, group, properties, metrics));
  11. if (cbForCommand == null) {
  12. return circuitBreakersByCommand.get(key.name());
  13. } else {
  14. return cbForCommand;
  15. }
  16. }
  17. public static HystrixCircuitBreaker getInstance(HystrixCommandKey key) {
  18. return circuitBreakersByCommand.get(key.name());
  19. }
  20. static void reset() {
  21. circuitBreakersByCommand.clear();
  22. }
  23. }

HystrixCircuitBreakerImpl是HystrixCircuitBreaker的实现,allowRequest()、isOpen()、markSuccess()都会在HystrixCircuitBreakerImpl有默认的实现。

  1. static class HystrixCircuitBreakerImpl implements HystrixCircuitBreaker {
  2. private final HystrixCommandProperties properties;
  3. private final HystrixCommandMetrics metrics;
  4. /* 变量circuitOpen来代表断路器的状态,默认是关闭 */
  5. private AtomicBoolean circuitOpen = new AtomicBoolean(false);
  6. /* 变量circuitOpenedOrLastTestedTime记录着断路恢复计时器的初始时间,用于Open状态向Close状态的转换 */
  7. private AtomicLong circuitOpenedOrLastTestedTime = new AtomicLong();
  8. protected HystrixCircuitBreakerImpl(HystrixCommandKey key, HystrixCommandGroupKey commandGroup, HystrixCommandProperties properties, HystrixCommandMetrics metrics) {
  9. this.properties = properties;
  10. this.metrics = metrics;
  11. }
  12. /*用于关闭熔断器并重置统计数据*/
  13. public void markSuccess() {
  14. if (circuitOpen.get()) {
  15. if (circuitOpen.compareAndSet(true, false)) {
  16. //win the thread race to reset metrics
  17. //Unsubscribe from the current stream to reset the health counts stream. This only affects the health counts view,
  18. //and all other metric consumers are unaffected by the reset
  19. metrics.resetStream();
  20. }
  21. }
  22. }
  23. @Override
  24. public boolean allowRequest() {
  25. //是否设置强制开启
  26. if (properties.circuitBreakerForceOpen().get()) {
  27. return false;
  28. }
  29. if (properties.circuitBreakerForceClosed().get()) {//是否设置强制关闭
  30. isOpen();
  31. // properties have asked us to ignore errors so we will ignore the results of isOpen and just allow all traffic through
  32. return true;
  33. }
  34. return !isOpen() || allowSingleTest();
  35. }
  36. public boolean allowSingleTest() {
  37. long timeCircuitOpenedOrWasLastTested = circuitOpenedOrLastTestedTime.get();
  38. //获取熔断恢复计时器记录的初始时间circuitOpenedOrLastTestedTime,然后判断以下两个条件是否同时满足:
  39. // 1) 熔断器的状态为开启状态(circuitOpen.get() == true)
  40. // 2) 当前时间与计时器初始时间之差大于计时器阈值circuitBreakerSleepWindowInMilliseconds(默认为 5 秒)
  41. //如果同时满足的话,表示可以从Open状态向Close状态转换。Hystrix会通过CAS操作将circuitOpenedOrLastTestedTime设为当前时间,并返回true。如果不同时满足,返回false,代表熔断器关闭或者计时器时间未到。
  42. if (circuitOpen.get() && System.currentTimeMillis() > timeCircuitOpenedOrWasLastTested + properties.circuitBreakerSleepWindowInMilliseconds().get()) {
  43. // We push the 'circuitOpenedTime' ahead by 'sleepWindow' since we have allowed one request to try.
  44. // If it succeeds the circuit will be closed, otherwise another singleTest will be allowed at the end of the 'sleepWindow'.
  45. if (circuitOpenedOrLastTestedTime.compareAndSet(timeCircuitOpenedOrWasLastTested, System.currentTimeMillis())) {
  46. // if this returns true that means we set the time so we'll return true to allow the singleTest
  47. // if it returned false it means another thread raced us and allowed the singleTest before we did
  48. return true;
  49. }
  50. }
  51. return false;
  52. }
  53. @Override
  54. public boolean isOpen() {
  55. if (circuitOpen.get()) {//获取断路器的状态
  56. // if we're open we immediately return true and don't bother attempting to 'close' ourself as that is left to allowSingleTest and a subsequent successful test to close
  57. return true;
  58. }
  59. // Metrics数据中获取HealthCounts对象
  60. HealthCounts health = metrics.getHealthCounts();
  61. // 检查对应的请求总数(totalCount)是否小于属性中的请求容量阈值circuitBreakerRequestVolumeThreshold,默认20,如果是的话表示熔断器可以保持关闭状态,返回false
  62. if (health.getTotalRequests() < properties.circuitBreakerRequestVolumeThreshold().get()) {
  63. return false;
  64. }
  65. //不满足请求总数条件,就再检查错误比率(errorPercentage)是否小于属性中的错误百分比阈值(circuitBreakerErrorThresholdPercentage,默认 50),如果是的话表示断路器可以保持关闭状态,返回 false
  66. if (health.getErrorPercentage() < properties.circuitBreakerErrorThresholdPercentage().get()) {
  67. return false;
  68. } else {
  69. // 如果超过阈值,Hystrix会判定服务的某些地方出现了问题,因此通过CAS操作将断路器设为开启状态,并记录此时的系统时间作为定时器初始时间,最后返回 true
  70. if (circuitOpen.compareAndSet(false, true)) {
  71. circuitOpenedOrLastTestedTime.set(System.currentTimeMillis());
  72. return true;
  73. } else {
  74. return true;
  75. }
  76. }
  77. }
  78. }

3.4、熔断器小结

每个熔断器默认维护10个bucket,每秒一个bucket,每个blucket记录成功,失败,超时,拒绝的状态,默认错误超过50%且10秒内超过20个请求进行中断拦截。下图显示HystrixCommand或HystrixObservableCommand如何与HystrixCircuitBreaker及其逻辑和决策流程进行交互,包括计数器在断路器中的行为。

四、回退降级

4.1、降级

所谓降级,就是指在在Hystrix执行非核心链路功能失败的情况下,我们如何处理,比如我们返回默认值等。如果我们要回退或者降级处理,代码上需要实现HystrixCommand.getFallback()方法或者是HystrixObservableCommand. HystrixObservableCommand()。

  1. public class CommandHelloFailure extends HystrixCommand<String> {
  2. private final String name;
  3. public CommandHelloFailure(String name) {
  4. super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
  5. this.name = name;
  6. }
  7. @Override
  8. protected String run() {
  9. throw new RuntimeException("this command always fails");
  10. }
  11. @Override
  12. protected String getFallback() {
  13. return "Hello Failure " + name + "!";
  14. }
  15. }

4.2、Hystrix的降级回退方式

Hystrix一共有如下几种降级回退模式:

4.2.1、Fail Fast 快速失败

  1. @Override
  2. protected String run() {
  3. if (throwException) {
  4. throw new RuntimeException("failure from CommandThatFailsFast");
  5. } else {
  6. return "success";
  7. }
  8. }

如果我们实现的是HystrixObservableCommand.java则 重写 resumeWithFallback方法

  1. @Override
  2. protected Observable<String> resumeWithFallback() {
  3. if (throwException) {
  4. return Observable.error(new Throwable("failure from CommandThatFailsFast"));
  5. } else {
  6. return Observable.just("success");
  7. }
  8. }

4.2.2、Fail Silent 无声失败

返回null,空Map,空List

 

  1. @Override
  2. protected String getFallback() {
  3. return null;
  4. }
  5. @Override
  6. protected List<String> getFallback() {
  7. return Collections.emptyList();
  8. }
  9. @Override
  10. protected Observable<String> resumeWithFallback() {
  11. return Observable.empty();
  12. }

4.2.3、Fallback: Static 返回默认值

回退的时候返回静态嵌入代码中的默认值,这样就不会导致功能以Fail Silent的方式被清楚,也就是用户看不到任何功能了。而是按照一个默认的方式显示。

  1. @Override
  2. protected Boolean getFallback() {
  3. return true;
  4. }
  5. @Override
  6. protected Observable<Boolean> resumeWithFallback() {
  7. return Observable.just( true );
  8. }

4.2.4、Fallback: Stubbed 自己组装一个值返回

当我们执行返回的结果是一个包含多个字段的对象时,则会以Stubbed 的方式回退。Stubbed 值我们建议在实例化Command的时候就设置好一个值。以countryCodeFromGeoLookup为例,countryCodeFromGeoLookup的值,是在我们调用的时候就注册进来初始化好的。CommandWithStubbedFallback command = new CommandWithStubbedFallback(1234, "china");主要代码如下:

  1. public class CommandWithStubbedFallback extends HystrixCommand<UserAccount> {
  2. protected CommandWithStubbedFallback(int customerId, String countryCodeFromGeoLookup) {
  3. super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
  4. this.customerId = customerId;
  5. this.countryCodeFromGeoLookup = countryCodeFromGeoLookup;
  6. }
  7. @Override
  8. protected UserAccount getFallback() {
  9. /**
  10. * Return stubbed fallback with some static defaults, placeholders,
  11. * and an injected value 'countryCodeFromGeoLookup' that we'll use
  12. * instead of what we would have retrieved from the remote service.
  13. */
  14. return new UserAccount(customerId, "Unknown Name",
  15. countryCodeFromGeoLookup, true, true, false);
  16. }

4.2.5、Fallback: Cache via Network 利用远程缓存

通过远程缓存的方式。在失败的情况下再发起一次remote请求,不过这次请求的是一个缓存比如redis。由于是又发起一起远程调用,所以会重新封装一次Command,这个时候要注意,执行fallback的线程一定要跟主线程区分开,也就是重新命名一个ThreadPoolKey。

 

  1. public class CommandWithFallbackViaNetwork extends HystrixCommand<String> {
  2. private final int id;
  3. protected CommandWithFallbackViaNetwork(int id) {
  4. super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceX"))
  5. .andCommandKey(HystrixCommandKey.Factory.asKey("GetValueCommand")));
  6. this.id = id;
  7. }
  8. @Override
  9. protected String run() {
  10. // RemoteServiceXClient.getValue(id);
  11. throw new RuntimeException("force failure for example");
  12. }
  13. @Override
  14. protected String getFallback() {
  15. return new FallbackViaNetwork(id).execute();
  16. }
  17. private static class FallbackViaNetwork extends HystrixCommand<String> {
  18. private final int id;
  19. public FallbackViaNetwork(int id) {
  20. super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceX"))
  21. .andCommandKey(HystrixCommandKey.Factory.asKey("GetValueFallbackCommand"))
  22. // use a different threadpool for the fallback command
  23. // so saturating the RemoteServiceX pool won't prevent
  24. // fallbacks from executing
  25. .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("RemoteServiceXFallback")));
  26. this.id = id;
  27. }
  28. @Override
  29. protected String run() {
  30. MemCacheClient.getValue(id);
  31. }
  32. @Override
  33. protected String getFallback() {
  34. // the fallback also failed
  35. // so this fallback-of-a-fallback will
  36. // fail silently and return null
  37. return null;
  38. }
  39. }
  40. }

4.2.6、Primary + Secondary with Fallback 主次方式回退(主要和次要)

这个有点类似我们日常开发中需要上线一个新功能,但为了防止新功能上线失败可以回退到老的代码,我们会做一个开关比如使用zookeeper做一个配置开关,可以动态切换到老代码功能。那么Hystrix它是使用通过一个配置来在两个command中进行切换。

 

  1. /**
  2. * Sample {@link HystrixCommand} pattern using a semaphore-isolated command
  3. * that conditionally invokes thread-isolated commands.
  4. */
  5. public class CommandFacadeWithPrimarySecondary extends HystrixCommand<String> {
  6. private final static DynamicBooleanProperty usePrimary = DynamicPropertyFactory.getInstance().getBooleanProperty("primarySecondary.usePrimary", true);
  7. private final int id;
  8. public CommandFacadeWithPrimarySecondary(int id) {
  9. super(Setter
  10. .withGroupKey(HystrixCommandGroupKey.Factory.asKey("SystemX"))
  11. .andCommandKey(HystrixCommandKey.Factory.asKey("PrimarySecondaryCommand"))
  12. .andCommandPropertiesDefaults(
  13. // we want to default to semaphore-isolation since this wraps
  14. // 2 others commands that are already thread isolated
  15. // 采用信号量的隔离方式
  16. HystrixCommandProperties.Setter()
  17. .withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE)));
  18. this.id = id;
  19. }
  20. //通过DynamicPropertyFactory来路由到不同的command
  21. @Override
  22. protected String run() {
  23. if (usePrimary.get()) {
  24. return new PrimaryCommand(id).execute();
  25. } else {
  26. return new SecondaryCommand(id).execute();
  27. }
  28. }
  29. @Override
  30. protected String getFallback() {
  31. return "static-fallback-" + id;
  32. }
  33. @Override
  34. protected String getCacheKey() {
  35. return String.valueOf(id);
  36. }
  37. private static class PrimaryCommand extends HystrixCommand<String> {
  38. private final int id;
  39. private PrimaryCommand(int id) {
  40. super(Setter
  41. .withGroupKey(HystrixCommandGroupKey.Factory.asKey("SystemX"))
  42. .andCommandKey(HystrixCommandKey.Factory.asKey("PrimaryCommand"))
  43. .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("PrimaryCommand"))
  44. .andCommandPropertiesDefaults(
  45. // we default to a 600ms timeout for primary
  46. HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(600)));
  47. this.id = id;
  48. }
  49. @Override
  50. protected String run() {
  51. // perform expensive 'primary' service call
  52. return "responseFromPrimary-" + id;
  53. }
  54. }
  55. private static class SecondaryCommand extends HystrixCommand<String> {
  56. private final int id;
  57. private SecondaryCommand(int id) {
  58. super(Setter
  59. .withGroupKey(HystrixCommandGroupKey.Factory.asKey("SystemX"))
  60. .andCommandKey(HystrixCommandKey.Factory.asKey("SecondaryCommand"))
  61. .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("SecondaryCommand"))
  62. .andCommandPropertiesDefaults(
  63. // we default to a 100ms timeout for secondary
  64. HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(100)));
  65. this.id = id;
  66. }
  67. @Override
  68. protected String run() {
  69. // perform fast 'secondary' service call
  70. return "responseFromSecondary-" + id;
  71. }
  72. }
  73. public static class UnitTest {
  74. @Test
  75. public void testPrimary() {
  76. HystrixRequestContext context = HystrixRequestContext.initializeContext();
  77. try {
  78. //将属性"primarySecondary.usePrimary"设置为true,则走PrimaryCommand;设置为false,则走SecondaryCommand
  79. ConfigurationManager.getConfigInstance().setProperty("primarySecondary.usePrimary", true);
  80. assertEquals("responseFromPrimary-20", new CommandFacadeWithPrimarySecondary(20).execute());
  81. } finally {
  82. context.shutdown();
  83. ConfigurationManager.getConfigInstance().clear();
  84. }
  85. }
  86. @Test
  87. public void testSecondary() {
  88. HystrixRequestContext context = HystrixRequestContext.initializeContext();
  89. try {
  90. //将属性"primarySecondary.usePrimary"设置为true,则走PrimaryCommand;设置为false,则走SecondaryCommand
  91. ConfigurationManager.getConfigInstance().setProperty("primarySecondary.usePrimary", false);
  92. assertEquals("responseFromSecondary-20", new CommandFacadeWithPrimarySecondary(20).execute());
  93. } finally {
  94. context.shutdown();
  95. ConfigurationManager.getConfigInstance().clear();
  96. }
  97. }
  98. }
  99. }

4.3、回退降级小结

降级的处理方式,返回默认值,返回缓存里面的值(包括远程缓存比如redis和本地缓存比如jvmcache)。
但回退的处理方式也有不适合的场景:
1、写操作
2、批处理
3、计算
以上几种情况如果失败,则程序就要将错误返回给调用者。

总结

Hystrix为我们提供了一套线上系统容错的技术实践方法,我们通过在系统中引入Hystrix的jar包可以很方便的使用线程隔离、熔断、回退等技术。同时它还提供了监控页面配置,方便我们管理查看每个接口的调用情况。像spring cloud这种微服务构建模式中也引入了Hystrix,我们可以放心使用Hystrix的线程隔离技术,来防止雪崩这种可怕的致命性线上故障。

附:SpringCloud之系列汇总跳转地址 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小舞很执着/article/detail/978724
推荐阅读
相关标签
  

闽ICP备14008679号