深入Spring Boot:快速集成Dubbo + Hystrix

背景

Hystrix 旨在通過控制那些訪問遠(yuǎn)程系統(tǒng)搔体、服務(wù)和第三方庫的節(jié)點臭杰,從而對延遲和故障提供更強大的容錯能力我衬。Hystrix具備擁有回退機制和斷路器功能的線程和信號隔離,請求緩存和請求打包斋日,以及監(jiān)控和配置等功能牲览。

Dubbo是Alibaba開源的,目前國內(nèi)最流行的java rpc框架恶守。

本文介紹在spring應(yīng)用里第献,怎么把Dubbo和Hystrix結(jié)合起來使用。

spring boot官方提供了對hystrix的集成兔港,直接在pom.xml里加入依賴:

<dependency>

????<groupId>org.springframework.cloud</groupId>

????<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>

????<version>1.4.4.RELEASE</version>

</dependency>

然后在Application類上增加@EnableHystrix來啟用hystrix starter:

@SpringBootApplication

@EnableHystrix

publicclassProviderApplication {

配置Provider端

在Dubbo的Provider上增加@HystrixCommand配置庸毫,這樣子調(diào)用就會經(jīng)過Hystrix代理。

@Service(version = "1.0.0")

publicclassHelloServiceImpl implementsHelloService {

????@HystrixCommand(commandProperties = {

????????????????????@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),

????????????????????@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000") })

????@Override

????publicString sayHello(String name) {

????????// System.out.println("async provider received: " + name);

????????// return "annotation: hello, " + name;

????????thrownewRuntimeException("Exception to show hystrix enabled.");

????}

}

配置Consumer端

對于Consumer端衫樊,則可以增加一層method調(diào)用飒赃,并在method上配置@HystrixCommand。當(dāng)調(diào)用出錯時科侈,會走到fallbackMethod = "reliable"的調(diào)用里载佳。

@Reference(version = "1.0.0")

privateHelloService demoService;


@HystrixCommand(fallbackMethod = "reliable")

publicString doSayHello(String name) {

????returndemoService.sayHello(name);

}

publicString reliable(String name) {

????return"hystrix fallback value";

}

通過上面的配置,很簡單地就完成了Spring Boot里Dubbo + Hystrix的集成臀栈。

傳統(tǒng)Spring Annotation應(yīng)用

Demo地址

傳統(tǒng)spring annotation應(yīng)用的配置其實也很簡單蔫慧,和spring boot應(yīng)用不同的是:

顯式配置Spring AOP支持:@EnableAspectJAutoProxy

顯式通過@Configuration配置HystrixCommandAspectBean。


@Configuration

@EnableDubbo(scanBasePackages = "com.alibaba.dubbo.samples.annotation.action")

@PropertySource("classpath:/spring/dubbo-consumer.properties")

@ComponentScan(value = {"com.alibaba.dubbo.samples.annotation.action"})

@EnableAspectJAutoProxy

staticpublicclassConsumerConfiguration {


????@Bean

????publicHystrixCommandAspect hystrixCommandAspect() {

????????returnnewHystrixCommandAspect();

????}

}


Hystrix集成Spring AOP原理

在上面的例子里可以看到权薯,Hystrix對Spring的集成是通過Spring AOP來實現(xiàn)的藕漱。下面簡單分析下實現(xiàn)。


@Aspect

publicclassHystrixCommandAspect {

????@Pointcut("@annotation(com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand)")

????publicvoidhystrixCommandAnnotationPointcut() {

????}

????@Pointcut("@annotation(com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser)")

????publicvoidhystrixCollapserAnnotationPointcut() {

????}


????@Around("hystrixCommandAnnotationPointcut() || hystrixCollapserAnnotationPointcut()")

????publicObject methodsAnnotatedWithHystrixCommand(finalProceedingJoinPoint joinPoint) throwsThrowable {

????????Method method = getMethodFromTarget(joinPoint);

????????Validate.notNull(method, "failed to get method from joinPoint: %s", joinPoint);

????????if(method.isAnnotationPresent(HystrixCommand.class) && method.isAnnotationPresent(HystrixCollapser.class)) {

????????????thrownewIllegalStateException("method cannot be annotated with HystrixCommand and HystrixCollapser "+

????????????????????"annotations at the same time");

????????}

????????MetaHolderFactory metaHolderFactory = META_HOLDER_FACTORY_MAP.get(HystrixPointcutType.of(method));

????????MetaHolder metaHolder = metaHolderFactory.create(joinPoint);

????????HystrixInvokable invokable = HystrixCommandFactory.getInstance().create(metaHolder);

????????ExecutionType executionType = metaHolder.isCollapserAnnotationPresent() ?

????????????????metaHolder.getCollapserExecutionType() : metaHolder.getExecutionType();


????????Object result;

????????try{

????????????if(!metaHolder.isObservable()) {

????????????????result = CommandExecutor.execute(invokable, executionType, metaHolder);

????????????} else{

????????????????result = executeObservable(invokable, executionType, metaHolder);

????????????}

????????} catch(HystrixBadRequestException e) {

????????????throwe.getCause() != null? e.getCause() : e;

????????} catch(HystrixRuntimeException e) {

????????????throwhystrixRuntimeExceptionToThrowable(metaHolder, e);

????????}

????????returnresult;

????}

HystrixCommandAspect里定義了兩個注解的AspectJ Pointcut:@HystrixCommand,@HystrixCollapser崭闲。所有帶這兩個注解的spring bean都會經(jīng)過AOP處理

在@AroundAOP處理函數(shù)里,可以看到Hystrix會創(chuàng)建出HystrixInvokable威蕉,再通過CommandExecutor來執(zhí)行

spring-cloud-starter-netflix-hystrix的代碼分析

@EnableHystrix引入了@EnableCircuitBreaker刁俭,@EnableCircuitBreaker引入了EnableCircuitBreakerImportSelector

@EnableCircuitBreaker

public@interfaceEnableHystrix {

}

@Import(EnableCircuitBreakerImportSelector.class)

public@interfaceEnableCircuitBreaker {

}

EnableCircuitBreakerImportSelector繼承了SpringFactoryImportSelector<EnableCircuitBreaker>,使spring加載META-INF/spring.factories里的EnableCircuitBreaker聲明的配置在META-INF/spring.factories里可以找到下面的配置韧涨,也就是引入了HystrixCircuitBreakerConfiguration牍戚。

org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker=\

org.springframework.cloud.netflix.hystrix.HystrixCircuitBreakerConfiguration

在HystrixCircuitBreakerConfiguration里可以發(fā)現(xiàn)創(chuàng)建了HystrixCommandAspect


@Configuration

publicclassHystrixCircuitBreakerConfiguration {


????@Bean

????publicHystrixCommandAspect hystrixCommandAspect() {

????????returnnewHystrixCommandAspect();

????}

可見spring-cloud-starter-netflix-hystrix實際上也是創(chuàng)建了HystrixCommandAspect來集成Hystrix。

另外spring-cloud-starter-netflix-hystrix里還有metrics, health, dashboard等集成虑粥。

總結(jié)

對于dubbo provider的@Service是一個spring bean如孝,直接在上面配置@HystrixCommand即可

對于dubbo consumer的@Reference,可以通過加一層簡單的spring method包裝娩贷,配置@HystrixCommand即可

Hystrix本身提供HystrixCommandAspect來集成Spring AOP第晰,配置了@HystrixCommand和@HystrixCollapser的spring method都會被Hystrix處理

歡迎學(xué)Java和大數(shù)據(jù)的朋友們加入java架構(gòu)交流: 855835163

加群鏈接:https://jq.qq.com/?_wv=1027&k=5dPqXGI

群內(nèi)提供免費的架構(gòu)資料還有:Java工程化、高性能及分布式、高性能茁瘦、深入淺出品抽。高架構(gòu)。性能調(diào)優(yōu)甜熔、Spring圆恤,MyBatis,Netty源碼分析和大數(shù)據(jù)等多個知識點高級進(jìn)階干貨的免費直播講解 ?可以進(jìn)來一起學(xué)習(xí)交流哦

直播課堂地址:https://ke.qq.com/course/260263?flowToken=1007014

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末腔稀,一起剝皮案震驚了整個濱河市盆昙,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌焊虏,老刑警劉巖淡喜,帶你破解...
    沈念sama閱讀 217,277評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異炕淮,居然都是意外死亡拆火,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評論 3 393
  • 文/潘曉璐 我一進(jìn)店門涂圆,熙熙樓的掌柜王于貴愁眉苦臉地迎上來们镜,“玉大人,你說我怎么就攤上這事润歉∧O粒” “怎么了?”我有些...
    開封第一講書人閱讀 163,624評論 0 353
  • 文/不壞的土叔 我叫張陵踩衩,是天一觀的道長嚼鹉。 經(jīng)常有香客問我,道長驱富,這世上最難降的妖魔是什么锚赤? 我笑而不...
    開封第一講書人閱讀 58,356評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮褐鸥,結(jié)果婚禮上线脚,老公的妹妹穿的比我還像新娘。我一直安慰自己叫榕,他們只是感情好浑侥,可當(dāng)我...
    茶點故事閱讀 67,402評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著晰绎,像睡著了一般寓落。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上荞下,一...
    開封第一講書人閱讀 51,292評論 1 301
  • 那天伶选,我揣著相機與錄音史飞,去河邊找鬼。 笑死考蕾,一個胖子當(dāng)著我的面吹牛祸憋,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播肖卧,決...
    沈念sama閱讀 40,135評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼蚯窥,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了塞帐?” 一聲冷哼從身側(cè)響起拦赠,我...
    開封第一講書人閱讀 38,992評論 0 275
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎葵姥,沒想到半個月后荷鼠,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,429評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡榔幸,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,636評論 3 334
  • 正文 我和宋清朗相戀三年允乐,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片削咆。...
    茶點故事閱讀 39,785評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡牍疏,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出拨齐,到底是詐尸還是另有隱情鳞陨,我是刑警寧澤,帶...
    沈念sama閱讀 35,492評論 5 345
  • 正文 年R本政府宣布瞻惋,位于F島的核電站厦滤,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏歼狼。R本人自食惡果不足惜掏导,卻給世界環(huán)境...
    茶點故事閱讀 41,092評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望羽峰。 院中可真熱鬧碘菜,春花似錦、人聲如沸限寞。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽履植。三九已至,卻和暖如春悄晃,著一層夾襖步出監(jiān)牢的瞬間玫霎,已是汗流浹背凿滤。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留庶近,地道東北人翁脆。 一個月前我還...
    沈念sama閱讀 47,891評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像鼻种,于是被迫代替她去往敵國和親反番。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,713評論 2 354

推薦閱讀更多精彩內(nèi)容