中文字幕在线观看,亚洲а∨天堂久久精品9966,亚洲成a人片在线观看你懂的,亚洲av成人片无码网站,亚洲国产精品无码久久久五月天

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

2018-07-02    來源:importnew

容器云強(qiáng)勢(shì)上線!快速搭建集群,上萬Linux鏡像隨意使用

背景

Hystrix 旨在通過控制那些訪問遠(yuǎn)程系統(tǒng)、服務(wù)和第三方庫的節(jié)點(diǎn),從而對(duì)延遲和故障提供更強(qiáng)大的容錯(cuò)能力。Hystrix具備擁有回退機(jī)制和斷路器功能的線程和信號(hào)隔離,請(qǐng)求緩存和請(qǐng)求打包,以及監(jiān)控和配置等功能。

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

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

  • https://github.com/Netflix/Hystrix
  • https://github.com/apache/incubator-dubbo

Spring Boot應(yīng)用

Demo地址

生成dubbo集成spring boot的應(yīng)用

對(duì)于不熟悉dubbo 集成spring boot應(yīng)用的同學(xué),可以在這里直接生成dubbo + spring boot的工程:?http://start.dubbo.io/

配置spring-cloud-starter-netflix-hystrix

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來啟用hystrix starter:

@SpringBootApplication
@EnableHystrix
public class ProviderApplication {

配置Provider端

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

@Service(version = "1.0.0")
public class HelloServiceImpl implements HelloService {
    @HystrixCommand(commandProperties = {
                    @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000") })
    @Override
    public String sayHello(String name) {
        // System.out.println("async provider received: " + name);
        // return "annotation: hello, " + name;
        throw new RuntimeException("Exception to show hystrix enabled.");
    }
}

配置Consumer端

對(duì)于Consumer端,則可以增加一層method調(diào)用,并在method上配置@HystrixCommand。當(dāng)調(diào)用出錯(cuò)時(shí),會(huì)走到fallbackMethod = "reliable"的調(diào)用里。

    @Reference(version = "1.0.0")
    private HelloService demoService;

    @HystrixCommand(fallbackMethod = "reliable")
    public String doSayHello(String name) {
        return demoService.sayHello(name);
    }
    public String reliable(String name) {
        return "hystrix fallback value";
    }

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

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

Demo地址

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

  1. 顯式配置Spring AOP支持:@EnableAspectJAutoProxy
  2. 顯式通過@Configuration配置HystrixCommandAspect?Bean。
    @Configuration
    @EnableDubbo(scanBasePackages = "com.alibaba.dubbo.samples.annotation.action")
    @PropertySource("classpath:/spring/dubbo-consumer.properties")
    @ComponentScan(value = {"com.alibaba.dubbo.samples.annotation.action"})
    @EnableAspectJAutoProxy
    static public class ConsumerConfiguration {

        @Bean
        public HystrixCommandAspect hystrixCommandAspect() {
            return new HystrixCommandAspect();
        }
    }

 

Hystrix集成Spring AOP原理

在上面的例子里可以看到,Hystrix對(duì)Spring的集成是通過Spring AOP來實(shí)現(xiàn)的。下面簡單分析下實(shí)現(xià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 {
        Method method = getMethodFromTarget(joinPoint);
        Validate.notNull(method, "failed to get method from joinPoint: %s", joinPoint);
        if (method.isAnnotationPresent(HystrixCommand.class) && method.isAnnotationPresent(HystrixCollapser.class)) {
            throw new IllegalStateException("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) {
            throw e.getCause() != null ? e.getCause() : e;
        } catch (HystrixRuntimeException e) {
            throw hystrixRuntimeExceptionToThrowable(metaHolder, e);
        }
        return result;
    }
  1. HystrixCommandAspect里定義了兩個(gè)注解的AspectJ Pointcut:@HystrixCommand,?@HystrixCollapser。所有帶這兩個(gè)注解的spring bean都會(huì)經(jīng)過AOP處理
  2. @Around?AOP處理函數(shù)里,可以看到Hystrix會(huì)創(chuàng)建出HystrixInvokable,再通過CommandExecutor來執(zhí)行

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

  1. @EnableHystrix?引入了@EnableCircuitBreaker@EnableCircuitBreaker引入了EnableCircuitBreakerImportSelector
    @EnableCircuitBreaker
    public @interface EnableHystrix {
    }
    
    @Import(EnableCircuitBreakerImportSelector.class)
    public @interface EnableCircuitBreaker {
    }
  2. 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
  3. HystrixCircuitBreakerConfiguration里可以發(fā)現(xiàn)創(chuàng)建了HystrixCommandAspect
    @Configuration
    public class HystrixCircuitBreakerConfiguration {
    
        @Bean
        public HystrixCommandAspect hystrixCommandAspect() {
            return new HystrixCommandAspect();
        }

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

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

總結(jié)

  • 對(duì)于dubbo provider的@Service是一個(gè)spring bean,直接在上面配置@HystrixCommand即可
  • 對(duì)于dubbo consumer的@Reference,可以通過加一層簡單的spring method包裝,配置@HystrixCommand即可
  • Hystrix本身提供HystrixCommandAspect來集成Spring AOP,配置了@HystrixCommand@HystrixCollapser的spring method都會(huì)被Hystrix處理

鏈接

  • https://github.com/Netflix/Hystrix
  • https://github.com/apache/incubator-dubbo
  • http://start.dubbo.io/
  • https://cloud.spring.io/spring-cloud-netflix/single/spring-cloud-netflix.html#_circuit_breaker_hystrix_clients

標(biāo)簽: 代碼

版權(quán)申明:本站文章部分自網(wǎng)絡(luò),如有侵權(quán),請(qǐng)聯(lián)系:west999com@outlook.com
特別注意:本站所有轉(zhuǎn)載文章言論不代表本站觀點(diǎn)!
本站所提供的圖片等素材,版權(quán)歸原作者所有,如需使用,請(qǐng)與原作者聯(lián)系。

上一篇:Java:關(guān)于值傳遞你需要了解的事情

下一篇:Java 配合 mitmproxy HTTPS 抓包調(diào)試