背景
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 {
在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端衫樊,則可以增加一層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)用
傳統(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的集成是通過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等集成虑粥。
對于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í)交流哦