Spring Cloud - 熔断(Hystrix)

图片.jpeg

Hystrix

1.三种状态

状态:关闭,开启和半开。最开始是关闭状态的,这个时候所有请求都可以通过;如果错误请求达到一定的阈值,就会变成开启状态,就会让所有请求短路,直接返回失败的响应;一段时间后,断路器会变成半开状态,如果下一个请求成功了,就关闭断路器,反之就开启断路器。”

我们先看看源码

requestVolumeThreshold 是最大请求数,10秒内的失败数超过20个,打开断路器
sleepWindowInMilliseconds 短路的多久的时间,尝试恢复 
errorThresholdPercentage 出错百分比阈值,当达到此阈值后,开始短路。默认50%

    public static class HystrixCommandMetricsConfig {
        private final int healthIntervalInMilliseconds;
        private final boolean rollingPercentileEnabled;
        private final int rollingPercentileNumberOfBuckets;
        private final int rollingPercentileBucketSizeInMilliseconds;
        private final int rollingCounterNumberOfBuckets;
        private final int rollingCounterBucketSizeInMilliseconds;

        public HystrixCommandMetricsConfig(int healthIntervalInMilliseconds, boolean rollingPercentileEnabled, int rollingPercentileNumberOfBuckets, int rollingPercentileBucketSizeInMilliseconds, int rollingCounterNumberOfBuckets, int rollingCounterBucketSizeInMilliseconds) {
            this.healthIntervalInMilliseconds = healthIntervalInMilliseconds;
            this.rollingPercentileEnabled = rollingPercentileEnabled;
            this.rollingPercentileNumberOfBuckets = rollingPercentileNumberOfBuckets;
            this.rollingPercentileBucketSizeInMilliseconds = rollingPercentileBucketSizeInMilliseconds;
            this.rollingCounterNumberOfBuckets = rollingCounterNumberOfBuckets;
            this.rollingCounterBucketSizeInMilliseconds = rollingCounterBucketSizeInMilliseconds;
        }

发现源码里面的构造函数向上找。如下所示


  public HystrixCommandConfiguration(HystrixCommandKey commandKey, HystrixThreadPoolKey threadPoolKey, HystrixCommandGroupKey groupKey, HystrixCommandConfiguration.HystrixCommandExecutionConfig executionConfig, HystrixCommandConfiguration.HystrixCommandCircuitBreakerConfig circuitBreakerConfig, HystrixCommandConfiguration.HystrixCommandMetricsConfig metricsConfig) {
        this.commandKey = commandKey;
        this.threadPoolKey = threadPoolKey;
        this.groupKey = groupKey;
        this.executionConfig = executionConfig;
        this.circuitBreakerConfig = circuitBreakerConfig;
        this.metricsConfig = metricsConfig;
    }

    public static HystrixCommandConfiguration sample(HystrixCommandKey commandKey, HystrixThreadPoolKey threadPoolKey, HystrixCommandGroupKey groupKey, HystrixCommandProperties commandProperties) {
        HystrixCommandConfiguration.HystrixCommandExecutionConfig executionConfig = new HystrixCommandConfiguration.HystrixCommandExecutionConfig((Integer)commandProperties.executionIsolationSemaphoreMaxConcurrentRequests().get(), (ExecutionIsolationStrategy)commandProperties.executionIsolationStrategy().get(), (Boolean)commandProperties.executionIsolationThreadInterruptOnTimeout().get(), (String)commandProperties.executionIsolationThreadPoolKeyOverride().get(), (Boolean)commandProperties.executionTimeoutEnabled().get(), (Integer)commandProperties.executionTimeoutInMilliseconds().get(), (Boolean)commandProperties.fallbackEnabled().get(), (Integer)commandProperties.fallbackIsolationSemaphoreMaxConcurrentRequests().get(), (Boolean)commandProperties.requestCacheEnabled().get(), (Boolean)commandProperties.requestLogEnabled().get());
        HystrixCommandConfiguration.HystrixCommandCircuitBreakerConfig circuitBreakerConfig = new HystrixCommandConfiguration.HystrixCommandCircuitBreakerConfig((Boolean)commandProperties.circuitBreakerEnabled().get(), (Integer)commandProperties.circuitBreakerErrorThresholdPercentage().get(), (Boolean)commandProperties.circuitBreakerForceClosed().get(), (Boolean)commandProperties.circuitBreakerForceOpen().get(), (Integer)commandProperties.circuitBreakerRequestVolumeThreshold().get(), (Integer)commandProperties.circuitBreakerSleepWindowInMilliseconds().get());
        HystrixCommandConfiguration.HystrixCommandMetricsConfig metricsConfig = new HystrixCommandConfiguration.HystrixCommandMetricsConfig((Integer)commandProperties.metricsHealthSnapshotIntervalInMilliseconds().get(), (Boolean)commandProperties.metricsRollingPercentileEnabled().get(), (Integer)commandProperties.metricsRollingPercentileWindowBuckets().get(), (Integer)commandProperties.metricsRollingPercentileWindowInMilliseconds().get(), (Integer)commandProperties.metricsRollingStatisticalWindowBuckets().get(), (Integer)commandProperties.metricsRollingStatisticalWindowInMilliseconds().get());
        return new HystrixCommandConfiguration(commandKey, threadPoolKey, groupKey, executionConfig, circuitBreakerConfig, metricsConfig);
    }

未命名1597314870.png
未命名1597314918.png

发现通过以上的构造方法,先去配置文件里面取,如果没有就去取上面的默认值。如图所示

2.工作原理

Hystrix主要使用的是RxJava来做异步请求,RxJava是一个异步框架,是对观察者模式的一个应用。Hystrix会把对每个微服务的请求放到线程池里面,具体分配到哪个线程池可以使用HystrixThreadPoolKey来指定。

通过源码我们发现 ,它的线程池 是由一个map维护的

    public static class Factory {
        static final ConcurrentHashMap<String, HystrixThreadPool> threadPools = new ConcurrentHashMap();

        public Factory() {
        }

        static HystrixThreadPool getInstance(HystrixThreadPoolKey threadPoolKey, Setter propertiesBuilder) {
            String key = threadPoolKey.name();
            HystrixThreadPool previouslyCached = (HystrixThreadPool)threadPools.get(key);
            if (previouslyCached != null) {
                return previouslyCached;
            } else {
                Class var4 = HystrixThreadPool.class;
                synchronized(HystrixThreadPool.class) {
                    if (!threadPools.containsKey(key)) {
                        threadPools.put(key, new HystrixThreadPool.HystrixThreadPoolDefault(threadPoolKey, propertiesBuilder));
                    }
                }

                return (HystrixThreadPool)threadPools.get(key);
            }
        }

通过看书我们发现
资源隔离。应用程序会被完全保护起来,即使依赖的一个服务出问题了,也不会影响到应用程序的其他部分。使用多个线程池就是一种资源隔离方式,也是默认的隔离方式。而且Hystrix底层是使用的RxJava,使用线程池可以让你很方便地实现异步操作

Hystrix提供了两种隔离方式:线程池隔离和信号量(Semaphore)隔离。

那么推荐使用哪个呢?
线程池隔离优缺点
优点:
保护应用程序以免受来自依赖故障的影响,指定依赖线程池饱和不会影响应用程序的其余部分。
当引入新客户端lib时,即使发生问题,也是在本lib中,并不会影响到其他内容。
当依赖从故障恢复正常时,应用程序会立即恢复正常的性能。
当应用程序一些配置参数错误时,线程池的运行状况会很快检测到这一点(通过增加错误,延迟, 超时,拒绝等),同时可以通过动态属性进行实时纠正错误的参数配置。
如果服务的性能有变化,需要实时调整,比如增加或者减少超时时间,更改重试次数,可以通过线 程池指标动态属性修改,而且不会影响到其他调用请求。
除了隔离优势外,hystrix拥有专门的线程池可提供内置的并发功能,使得可以在同步调用之上构 建异步门面(外观模式),为异步编程提供了支持(Hystrix引入了Rxjava异步框架)。
注意:尽管线程池提供了线程隔离,我们的客户端底层代码也必须要有超时设置或响应线程中断,不能 无限制的阻塞以致线程池一直饱和。

缺点:
线程池的主要缺点是增加了计算开销。每个命令的执行都在单独的线程完成,增加了排队、调度和上下文切换的开销。因此,要使用Hystrix,就必须接受它带来的开销,以换取它所提供的好处。
通常情况下,线程池引入的开销足够小,不会有重大的成本或性能影响。但对于一些访问延迟极低的服 务,如只依赖内存缓存,线程池引入的开销就比较明显了,这时候使用线程池隔离技术就不适合了,我 们需要考虑更轻量级的方式,如信号量隔离。

所以根据具体的场景我们考虑使用不同的隔离模式。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,390评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,821评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,632评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,170评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,033评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,098评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,511评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,204评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,479评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,572评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,341评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,893评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,171评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,486评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,676评论 2 335