SpringBoot如何整合Hystrix

1. SpringBoot如何整合Hystrix

1.1 导入maven依赖

        <!--hystrix官网-->
        <dependency>
            <groupId>com.netflix.hystrix</groupId>
            <artifactId>hystrix-core</artifactId>
            <version>1.5.18</version>
        </dependency>

        <dependency>
            <groupId>com.netflix.hystrix</groupId>
            <artifactId>hystrix-metrics-event-stream</artifactId>
            <version>1.5.18</version>
        </dependency>

        <dependency>
            <groupId>com.netflix.hystrix</groupId>
            <artifactId>hystrix-javanica</artifactId>
            <version>1.5.18</version>
        </dependency>

1.2 配置文件

在application.properties配置文件中加入如下配置:

hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=3000

将全局的默认超时时间由1s修改为3s,但是配置未起作用。

配置未生效的原因:

Archaius 默认支持两种方式来加载本地的配置文件:

  1. 默认情况下,Archaius 默认会加载classpath的config.properties文件。
  2. 在程序启动后,加入如下参数
    -Darchaius.configurationSource.additionalUrls=file:///apps/myapp/application.properties

1.3 如何使用

使用注解的方式,为方法添加hystrix断路器。

    @HystrixCommand(
            fallbackMethod = "fallConfigOfRemote"
            ,commandProperties = {
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1500")
            }
            )
    public String getConfigOfRemote(String id) {
        String url = "http://localhost:8001/getInfo";
        String doPost = "S";
        try {
            //调用远程服务,url,参数,socket超时时间
            doPost = HttpClientUtils.doPost(url, id, 10000);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return doPost;
    }

    private String fallConfigOfRemote(String id) {
        log.info("备选方案...");
        return "F";
    }

在resources\config.properties中进行配置:

#配置默认的超时时间
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=1000
#配置特定commandKey的超时时间(优先级最高)
hystrix.command.getConfigOfRemote.execution.isolation.thread.timeoutInMilliseconds=4000

使用Hystrix后,配置均会在com.netflix.hystrix.AbstractCommand#AbstractCommand类中组装。

[图片上传失败...(image-a9070e-1612084543977)]

注:需要注意的是,虽然在3个地方设置了 超时时间。但是只有4000ms的超时时间生效。

引申出两个问题?

1. hystrix配置的优先级是怎么样的呢?
2. 如何为某个方法配置不同的hystrix策略?

2. Hystrix配置

2.1 Hystrix配置的优先级

优先级从低到高的配置:

  1. 内置全局属性默认值:写死在代码中的值;
  2. 动态全局默认属性:通过配置文件配置全局的值;
  3. 内置实例默认值:写死在代码中的实例的值;
  4. 动态配置实例属性:通过配置文件配置特定实例的值;

注:全局配置是default的配置,而实例配置为commandKey配置。

2.2 CommandKey和CommandGroup

如何监控或者个性化的配置Hystrix参数?

默认情况下,Hystrix会使用类名作为CommandGroup,会使用方法名作为CommandKey。可以使用commandKey进行个性化的配置。参考【1.3 如何使用】

[图片上传失败...(image-95f991-1612084543977)]

2.3 详细配置

2.3.1 Execution

1. 设置Hystrix的隔离策略

配置 默认值
execution.isolation.strategy THREAD

表示HystrixCommand.run()的执行时的策略,有以下两种策略:

配置 属性
THREAD(默认值) 在单独的线程上执行,并发请求受线程池中的线程数限制
SEMAPHORE 在调用线程上执行,并发请求量受信号量计数限制
// 设置所有实例的默认值
hystrix.command.default.execution.isolation.strategy=…
// 设置实例HystrixCommandKey的此属性值
hystrix.command.HystrixCommandKey.execution.isolation.strategy=…

2. 设置调用者执行的超时时间

配置 默认值
execution.isolation.thread.timeoutInMilliseconds 1000ms
// 设置所有实例的默认值
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=…
// 设置实例HystrixCommandKey的此属性值
hystrix.command.HystrixCommandKey.execution.isolation.thread.timeoutInMilliseconds=…

3. 设置是否开启超时设置

配置 默认值
execution.timeout.enabled true
// 设置所有实例的默认值
hystrix.command.default.execution.timeout.enabled=…
// 设置实例HystrixCommandKey的此属性值
hystrix.command.HystrixCommandKey.execution.timeout.enabled=…

4. 设置是否超时时,中断HystrixCommand.run()的执行

配置 默认值
execution.isolation.thread.interruptOnTimeout true
// 设置所有实例的默认值
hystrix.command.default.execution.isolation.thread.interruptOnTimeout=…
// 设置实例HystrixCommandKey的此属性值
hystrix.command.HystrixCommandKey.execution.isolation.thread.interruptOnTimeout=…

5. 设置是否在取消任务执行时,中断HystrixCommand.run()的执行

配置 默认值
execution.isolation.thread.interruptOnCancel false
// 设置所有实例的默认值
hystrix.command.default.execution.isolation.thread.interruptOnCancel=…
// 设置实例HystrixCommandKey的此属性值
hystrix.command.HystrixCommandKey.execution.isolation.thread.interruptOnCancel

6. 使用SEMAPHORE策略时,设置最大的并发量

配置 默认值
execution.isolation.semaphore.maxConcurrentRequests 10
// 设置所有实例的默认值
hystrix.command.default.execution.isolation.semaphore.maxConcurrentRequests=…
// 设置实例HystrixCommandKey的此属性值
hystrix.command.HystrixCommandKey.execution.isolation.semaphore.maxConcurrentRequests=…

2.3.2 Fallback

以下属性控制HystrixCommand.getFallback()如何执行,这些属性对隔离策略THREADSEMAPHORE都起作用。

1. 设置从调用线程运行getFallback()方法允许的最大并发请求数

此属性设置从调用线程允许Hystrix.getFallback()方法允许的最大并发请求数,如果达到最大的并发量,则接下来的请求都会被拒绝并且抛出异常。

配置 默认值
fallback.isolation.semaphore.maxConcurrentRequests 10
// 设置所有实例的默认值
hystrix.command.default.fallback.isolation.semaphore.maxConcurrentRequests
// 设置实例HystrixCommandKey的此属性值
hystrix.command.HystrixCommandKey.fallback.isolation.semaphore.maxConcurrentRequests

2. 是否开启fallback功能

配置 默认值
hystrix.command.default.fallback.enabled true
// 设置所有实例的默认值
hystrix.command.default.fallback.enabled=…
// 设置实例HystrixCommandKey的此属性值
hystrix.command.HystrixCommandKey.fallback.enabled=…

2.3.3 断路器

控制断路器的行为。

1. 是否开启断路器功能

配置 默认值
circuitBreaker.enabled true
// 设置所有实例的默认值
hystrix.command.default.circuitBreaker.enabled=…
// 设置实例HystrixCommandKey的此属性值
hystrix.command.HystrixCommandKey.circuitBreaker.enabled=…

2. 该属性设置滚动窗口中使断路器跳闸的最小请求数量

默认值20。若是在10s(窗口时间)内,只收到19个请求且都失败了,则断路器也不会开启。

// 设置所有实例的默认值
hystrix.command.default.circuitBreaker.requestVolumeThreshold=…
// 设置实例HystrixCommandKey的此属性值
hystrix.command.HystrixCommandKey.circuitBreaker.requestVolumeThreshold=…

3. 设置断路时间

断路器跳闸后,在此值的时间内,hystrix会拒绝新的请求,只有过了这个时间,断路器才会打开闸门。默认值5000ms

// 设置所有实例的默认值
hystrix.command.default.circuitBreaker.sleepWindowInMilliseconds=…
// 设置实例HystrixCommandKey的此属性值
hystrix.command.HystrixCommandKey.circuitBreaker.sleepWindowInMilliseconds=…

4. 设置跳闸百分比

设置失败百分比的阈值,如果失败比率超过这个值,则断路器跳闸并且进入fallback状态。默认值:50

// 设置所有实例的默认值
hystrix.command.default.circuitBreaker=…
// 设置实例HystrixCommandKey的此属性值
hystrix.command.HystrixCommandKey.circuitBreaker.errorThresholdPercentage=…

5. 断路器强制开启

如果这个属性true强制断路器进入开路(跳闸)状态,它将拒绝所有请求。
此属性优先于circuitBreaker.forceClosed。默认值false

// 设置所有实例的默认值
hystrix.command.default.circuitBreaker.forceOpen=…
// 设置实例HystrixCommandKey的此属性值
hystrix.command.HystrixCommandKey.circuitBreaker.forceOpen=…

6. 断路器强制关闭

如果设置true,则强制使断路器进行关闭状态,此时会允许执行所有请求,无论是否失败的次数达到circuitBreaker.errorThresholdPercentage值。默认值:false。

// 设置所有实例的默认值
hystrix.command.default.circuitBreaker.forceClosed=…
// 设置实例HystrixCommandKey的此属性值
hystrix.command.HystrixCommandKey.circuitBreaker.forceClosed=…

2.3.4 Metrics (度量)

捕获和HystrixCommand以及HystrixObservableCommand执行信息相关的配置属性。

1. 设置统计窗口的持续时间(ms)

Hystrix保留断路器使用和发布指标的时间。默认值:10000

// 设置所有实例的默认值
hystrix.command.default.metrics.rollingStats.timeInMilliseconds=10000
// 设置实例HystrixCommandKey的此属性值
hystrix.command.HystrixCommandKey.metrics.rollingStats.timeInMilliseconds=10000

2. 设置滚动桶的数量

metrics.rollingStats.timeInMilliseconds % metrics.rollingStats.numBuckets == 01
如:10000/10、10000/20是正确的配置,但是10000/7错误的。默认值:10
注:在高并发的环境里,每个桶的时间长度建议大于100ms。

// 设置所有实例的默认值
hystrix.command.default.metrics.rollingStats.numBuckets=…
// 设置实例HystrixCommandKey的此属性值
hystrix.command.HystrixCommandKey.metrics.rollingStats.numBuckets=…

2.3.5 Request Context

该属性控制HystrixCommand使用到的Hystrix的上下文。

1. 是否开启请求缓存功能

默认值:true

// 设置所有实例的默认值
hystrix.command.default.requestCache.enabled=…
// 设置实例HystrixCommandKey的此属性值
hystrix.command.HystrixCommandKey.requestCache.enabled=…

2. 表示是否开启日志

表示是否开启日志,打印执行HystrixCommand的情况和事件。默认值true

// 设置所有实例的默认值
hystrix.command.default.requestLog.enabled=…
// 设置实例HystrixCommandKey的此属性值
hystrix.command.HystrixCommandKey.requestLog.enabled=…

2.3.6 Collapser Properties

设置请求合并请求。

1. 设置同时批量执行的请求的最大数量

默认值:Integer.MAX_VALUE

// 设置所有实例的默认值
hystrix.collapser.default.maxRequestsInBatch=…
// 设置实例HystrixCommandKey的此属性值
hystrix.collapser.HystrixCollapserKey.maxRequestsInBatch=…

2. 批量执行创建多久之后,再触发真正的请求

默认值:10

// 设置所有实例的默认值
hystrix.collapser.default.timerDelayInMilliseconds=…
// 设置实例HystrixCommandKey的此属性值
hystrix.collapser.HystrixCollapserKey.timerDelayInMilliseconds=…

3. 请求缓存

是否对HystrixCollapser.execute() 和 HystrixCollapser.queue()开启请求缓存
默认值:true

// 设置所有实例的默认值
hystrix.collapser.default.requestCache.enabled=…
// 设置实例HystrixCommandKey的此属性值
hystrix.collapser.HystrixCollapserKey.requestCache.enabled=…

2.3.7 ThreadPool配置

1. 核心线程数量

默认值:10

// 设置所有实例的默认值
hystrix.threadpool.default.coreSize=…
// 设置实例HystrixCommandKey的此属性值
hystrix.threadpool.HystrixThreadPoolKey.coreSize=…

2. 最大线程数量

在1.5.9中添加。此属性设置最大线程池大小。这是在不开始拒绝HystrixCommands的情况下可以支持的最大并发数量。请注意,此设置仅在您设置时生效allowMaximumSizeToDivergeFromCoreSize。在1.5.9之前,核心和最大尺寸始终相等。
默认值:10

// 设置所有实例的默认值
hystrix.threadpool.default.maximumSize=…
// 设置实例HystrixCommandKey的此属性值
hystrix.threadpool.HystrixThreadPoolKey.maximumSize=…

3. 队列大小

设置最大的BlockingQueue队列的值。如果设置-1,则使用SynchronousQueue队列(无限队列)。如果设置正数,则使用LinkedBlockingQueue队列。默认值:-1

// 设置所有实例的默认值
hystrix.threadpool.default.maxQueueSize=…
// 设置实例HystrixCommandKey的此属性值
hystrix.threadpool.HystrixThreadPoolKey.maxQueueSize=…

4. 拒绝阈值(动态设置队列大小)

因为maxQueueSize值不能被动态修改,所有通过设置此值可以实现动态修改等待队列长度。即等待的队列的数量大于queueSizeRejectionThreshold时(但是没有达到maxQueueSize值),则开始拒绝后续的请求进入队列。
默认值:5
注:如果设置-1,则属性不启作用。

// 设置所有实例的默认值
hystrix.threadpool.default.queueSizeRejectionThreshold=…
// 设置实例HystrixCommandKey的此属性值
hystrix.threadpool.HystrixThreadPoolKey.queueSizeRejectionThreshold=…

5. 设置空闲时间

设置线程空闲多长时间后,释放(maximumSize-coreSize )个线程。默认值1(分钟)

// 设置所有实例的默认值
hystrix.threadpool.default.keepAliveTimeMinutes=…
// 设置实例HystrixCommandKey的此属性值
hystrix.threadpool.HystrixThreadPoolKey.keepAliveTimeMinutes=…

6. 是否允许设置最大的线程数量

设置allowMaximumSizeToDivergeFromCoreSize值为true时,maximumSize才有作用
默认值:false

// 设置所有实例的默认值
hystrix.threadpool.default.allowMaximumSizeToDivergeFromCoreSize=…
// 设置实例HystrixCommandKey的此属性值
hystrix.threadpool.HystrixThreadPoolKey.allowMaximumSizeToDivergeFromCoreSize=…

推荐阅读

官网——Hystrix的参数配置
Hystrix常用功能介绍
Hystrix源码解析--从原生的lib开始使用hystrix(一)

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

推荐阅读更多精彩内容