在項(xiàng)目中直接使用hystrix的流程分析
什么是Hystrix
Hystrix是Netflix針對(duì)微服務(wù)分布式系統(tǒng)的熔斷保護(hù)中間件,當(dāng)我們的客戶端連接遠(yuǎn)程的微服務(wù)時(shí),有兩種情況需要考慮:首先,如果遠(yuǎn)程系統(tǒng)當(dāng)機(jī)了我們?cè)趺崔k?
其次,我們?nèi)绾喂芾韺?duì)遠(yuǎn)程微服務(wù)的調(diào)用性能,以保證每個(gè)微服務(wù)以最小延遲最快性能響應(yīng)?
Hystrix是一個(gè)有關(guān)延遲和失敗容錯(cuò)的開(kāi)源庫(kù)包,用來(lái)設(shè)計(jì)隔離訪問(wèn)遠(yuǎn)程系統(tǒng)端點(diǎn)或微服務(wù)等,防止級(jí)聯(lián)爆炸式的失敗,也就是由一個(gè)小問(wèn)題引起接二連三擴(kuò)大的
瘋狂的錯(cuò)誤爆炸直至整個(gè)系統(tǒng)癱瘓,能夠讓復(fù)雜的分布式系統(tǒng)更加靈活具有彈性。這篇文章給大家介紹下在項(xiàng)目中如何直接使用hystrix?
一、背景
最近由于一些背景原因,需要在項(xiàng)目中需要對(duì)接口進(jìn)行限流。所以就考慮到了直接使用Hystrix。但是呢,又不想直接使用SpringCloud,而是直接引入原生,現(xiàn)在發(fā)現(xiàn)挺好用的,所以記錄下來(lái),分享出來(lái)。
二、使用方式
2.1 Jar包引入
<dependency> <groupId>com.netflix.hystrix</groupId> <artifactId>hystrix-javanica</artifactId> <version>1.5.18</version> </dependency> <dependency> <groupId>com.netflix.hystrix</groupId> <artifactId>hystrix-core</artifactId> <version>1.5.18</version> </dependency>
引入兩個(gè)包,分別是Hystrix核心包,以及直接原生的Java包
2.2 配置文件
在Resources目錄下面,放上hystrix.properties文件。配置如下。
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=3000 hystrix.command.default.fallback.isolation.semaphore.maxConcurrentRequests=1000 hystrix.command.default.circuitBreaker.requestVolumeThreshold=20 hystrix.command.default.metrics.rollingStats.numBuckets=10 hystrix.command.default.metrics.rollingStats.timeInMilliseconds=10000 hystrix.command.default.circuitBreaker.sleepWindowInMilliseconds=5000 hystrix.command.default.circuitBreaker.errorThresholdPercentage=50 hystrix.command.default.circuitBreaker.forceOpen=false hystrix.command.default.circuitBreaker.forceClosed=false hystrix.command.default.requestCache.enabled=false hystrix.threadpool.default.coreSize=10 hystrix.threadpool.default.maximumSize=10 hystrix.threadpool.default.allowMaximumSizeToDivergeFromCoreSize=true hystrix.threadpool.default.keepAliveTimeMinutes=1 hystrix.threadpool.default.maxQueueSize=100 hystrix.threadpool.default.queueSizeRejectionThreshold=101 hystrix.threadpool.default.metrics.rollingStats.numBuckets=10 hystrix.threadpool.default.metrics.rollingStats.timeInMilliseconds=10000 #hystrix.timer.threadpool.default.coreSize = 10
這個(gè)是一部分配置,如果需要知道更多,可以Click-Github Hystrix Wiki
2.3 設(shè)置配置
設(shè)置Hystrix的配置
/**
* <p>熔斷器配置</p>
*
* @author fattycal@qq.com
* @since 2022/6/4
*/
@Configuration
public class HystrixConfig implements InitializingBean {
@Bean
public HystrixCommandAspect hystrixCommandAspect(){
// 初始化切面
return new HystrixCommandAspect();
}
@Override
public void afterPropertiesSet() throws Exception {
// 初始化熔斷器配置
// 清除配置
ConfigurationManager.getConfigInstance().clear();
// 加載配置文件
ConfigurationManager.loadCascadedPropertiesFromResources("hystrix");
}
}HystrixCommandAspect是jar包帶的切面,通過(guò)切面通知,找去需要熔斷的方法,然后進(jìn)行處理。
@Aspect
public class HystrixCommandAspect {
//...略
@Pointcut("@annotation(com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand)")
public void hystrixCommandAnnotationPointcut() {
}
@Pointcut("@annotation(com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser)")
public void hystrixCollapserAnnotationPointcut() {
}
@Around("hystrixCommandAnnotationPointcut() || hystrixCollapserAnnotationPointcut()")
public Object methodsAnnotatedWithHystrixCommand(final ProceedingJoinPoint joinPoint) throws Throwable {
// ... 略
}
}ConfigurationManager看看這名字,就知道是配置管理的,也不負(fù)眾望,的確是用來(lái)加載配置的。
2.4 實(shí)現(xiàn)代碼
/**
* <p>熔斷器測(cè)試</p>
*
* @author fattycal@qq.com
* @since 2022/6/4
*/
@RestController
public class HystrixTestController {
@GetMapping("/hystrix")
@HystrixCommand(commandKey = "hystrixTestController-getHello", threadPoolKey = "hystrixTestController-getHello",
fallbackMethod = "getHelloFallback")
public String getHello(){
try {
// 執(zhí)行太快不便于測(cè)試
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "TEST Hystrix";
}
public String getHelloFallback(Throwable error){
// 打印日志
System.out.println("TEST Hystrix: " + error.getMessage());
return "TEST Hystrix: " + error.getMessage();
}
}代碼沒(méi)有啥花里胡哨的,直接在需要熔斷的方法上面加上HystrixCommond。
commandKey和threadPoolKey是自己設(shè)置的,可以為這個(gè)方法定制線程數(shù)、核心線程等配置(在hystrix.properties中添加)。給出示例如下。
#-------------------------------------------------------------------
hystrix.threadpool.hystrixTestController-getHello.coreSize=1
hystrix.threadpool.hystrixTestController-getHello.maximumSize=2
hystrix.threadpool.hystrixTestController-getHello.maxQueueSize=1
hystrix.threadpool.hystrixTestController-getHello.queueSizeRejectionThreshold=2
#-------------------------------------------------------------------
至此,完成了所有的配置和準(zhǔn)備,接下來(lái)直接測(cè)試
三、測(cè)試試驗(yàn)
直接從Jmeter官網(wǎng)下載jmeter,拿到跑測(cè)試, 具體下載過(guò)程就不一樣展示了,直接貼出測(cè)試結(jié)果。

由于為這個(gè)方法設(shè)置的核心線程數(shù)、線程數(shù)、隊(duì)列數(shù)都不大,很容易測(cè)試出結(jié)果。我們可以從console中很明顯的看到熔斷器打開(kāi),說(shuō)明方法被執(zhí)行到。
在從Jmeter中查看一下結(jié)果,也是可以佐證我們的效果。測(cè)試圖如下:

四、總結(jié)
自此,整個(gè)流程是走完了,可以看到效果著實(shí)起來(lái)了。 Hystrix知識(shí)限流熔斷中的一種方案,大家可以結(jié)合實(shí)際情況做出更多的選擇。
相關(guān)文章
java Quartz定時(shí)器任務(wù)與Spring task定時(shí)的幾種實(shí)現(xiàn)方法
本篇文章主要介紹了java Quartz定時(shí)器任務(wù)與Spring task定時(shí)的幾種實(shí)現(xiàn)方法的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2017-02-02
POST方法給@RequestBody傳參數(shù)失敗的解決及原因分析
這篇文章主要介紹了POST方法給@RequestBody傳參數(shù)失敗的解決及原因分析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-10-10
SpringBoot快速入門及起步依賴解析(實(shí)例詳解)
SpringBoot?是由?Pivotal?團(tuán)隊(duì)提供的全新框架,其設(shè)計(jì)目的是用來(lái)簡(jiǎn)化?Spring?應(yīng)用的初始搭建以及開(kāi)發(fā)過(guò)程,這篇文章主要介紹了SpringBoot快速入門及起步依賴解析,需要的朋友可以參考下2022-10-10
解析Java中PriorityQueue優(yōu)先級(jí)隊(duì)列結(jié)構(gòu)的源碼及用法
優(yōu)先級(jí)隊(duì)列是一種隊(duì)列結(jié)構(gòu),是0個(gè)或多個(gè)元素的集合,每個(gè)元素都有一個(gè)優(yōu)先權(quán),PriorityQueue被內(nèi)置于JDK中,本文就來(lái)解析Java中PriorityQueue優(yōu)先級(jí)隊(duì)列結(jié)構(gòu)的源碼及用法.2016-05-05
通過(guò)代碼實(shí)例了解SpringBoot啟動(dòng)原理
這篇文章主要介紹了通過(guò)代碼實(shí)例了解SpringBoot啟動(dòng)原理,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-12-12
SpringBoot實(shí)現(xiàn)前后端分離國(guó)際化的示例詳解
Springboot國(guó)際化可以幫助使用者在不同語(yǔ)言環(huán)境中構(gòu)建應(yīng)用程序,這樣應(yīng)用程序可以有效地適應(yīng)不同語(yǔ)言文化背景下的用戶需求。本文主要介紹了SpringBoot實(shí)現(xiàn)前后端分離國(guó)際化的方法,需要的可以參考一下2023-02-02
Java中Lambda表達(dá)式之Lambda語(yǔ)法與作用域解析
這篇文章主要介紹了Java中Lambda表達(dá)式之Lambda語(yǔ)法與作用域解析重點(diǎn)介紹Lambda表達(dá)式基礎(chǔ)知識(shí),需要的朋友可以參考下2017-02-02
Springboot 整合 Dubbo/ZooKeeper 實(shí)現(xiàn) SOA 案例解析
這篇文章主要介紹了Springboot 整合 Dubbo/ZooKeeper 詳解 SOA 案例,需要的朋友可以參考下2017-11-11
java實(shí)現(xiàn)單機(jī)版五子棋小游戲
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)單機(jī)版五子棋小游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-12-12
把Jar文件轉(zhuǎn)成exe安裝文件的實(shí)現(xiàn)方法
下面小編就為大家?guī)?lái)一篇把Jar文件轉(zhuǎn)成exe安裝文件的實(shí)現(xiàn)方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-11-11

