背景
Hystrix 旨在通過(guò)控制那些訪問(wèn)遠(yuǎn)程系統(tǒng)、服務(wù)和第三方庫(kù)的節(jié)點(diǎn),從而對(duì)延遲和故障提供更強(qiáng)大的容錯(cuò)能力。Hystrix具備擁有回退機(jī)制和斷路器功能的線程和信號(hào)隔離,請(qǐng)求緩存和請(qǐng)求打包,以及監(jiān)控和配置等功能。
Dubbo是Alibaba開(kāi)源的,目前國(guó)內(nèi)最流行的java rpc框架。
本文介紹在spring應(yīng)用里,怎么把Dubbo和Hystrix結(jié)合起來(lái)使用。
spring boot官方提供了對(duì)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來(lái)啟用hystrix starter:
@SpringBootApplication
@EnableHystrix
publicclassProviderApplication {
在Dubbo的Provider上增加@HystrixCommand配置,這樣子調(diào)用就會(huì)經(jīng)過(guò)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.");
????}
}
對(duì)于Consumer端,則可以增加一層method調(diào)用,并在method上配置@HystrixCommand。當(dāng)調(diào)用出錯(cuò)時(shí),會(huì)走到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";
}
通過(guò)上面的配置,很簡(jiǎn)單地就完成了Spring Boot里Dubbo + Hystrix的集成。
傳統(tǒng)Spring Annotation應(yīng)用
傳統(tǒng)spring annotation應(yīng)用的配置其實(shí)也很簡(jiǎn)單,和spring boot應(yīng)用不同的是:
顯式配置Spring AOP支持:@EnableAspectJAutoProxy
顯式通過(guò)@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對(duì)Spring的集成是通過(guò)Spring AOP來(lái)實(shí)現(xiàn)的。下面簡(jiǎn)單分析下實(shí)現(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里定義了兩個(gè)注解的AspectJ Pointcut:@HystrixCommand,@HystrixCollapser。所有帶這兩個(gè)注解的spring bean都會(huì)經(jīng)過(guò)AOP處理
在@AroundAOP處理函數(shù)里,可以看到Hystrix會(huì)創(chuàng)建出HystrixInvokable,再通過(guò)CommandExecutor來(lái)執(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();
????}
可見(jiàn)spring-cloud-starter-netflix-hystrix實(shí)際上也是創(chuàng)建了HystrixCommandAspect來(lái)集成Hystrix。
另外spring-cloud-starter-netflix-hystrix里還有metrics, health, dashboard等集成。
對(duì)于dubbo provider的@Service是一個(gè)spring bean,直接在上面配置@HystrixCommand即可
對(duì)于dubbo consumer的@Reference,可以通過(guò)加一層簡(jiǎn)單的spring method包裝,配置@HystrixCommand即可
Hystrix本身提供HystrixCommandAspect來(lái)集成Spring AOP,配置了@HystrixCommand和@HystrixCollapser的spring method都會(huì)被Hystrix處理
歡迎學(xué)Java和大數(shù)據(jù)的朋友們加入java架構(gòu)交流: 855835163
加群鏈接:https://jq.qq.com/?_wv=1027&k=5dPqXGI
群內(nèi)提供免費(fèi)的架構(gòu)資料還有:Java工程化、高性能及分布式、高性能、深入淺出。高架構(gòu)。性能調(diào)優(yōu)、Spring,MyBatis,Netty源碼分析和大數(shù)據(jù)等多個(gè)知識(shí)點(diǎn)高級(jí)進(jìn)階干貨的免費(fèi)直播講解 ?可以進(jìn)來(lái)一起學(xué)習(xí)交流哦