欢迎访问昆山宝鼎软件有限公司网站! 设为首页 | 网站地图 | XML | RSS订阅 | 宝鼎邮箱 | 后台管理


新闻资讯

MENU

软件开发知识

+ name; throw new RuntimeException(Exception 次  来源:昆山软开发 时间:2018-06-25

原文出处: hengyunabc

配景

Hystrix 旨在通过节制那些会见长途系统、处事和第三方库的节点,劳务派遣管理系统,从而对延迟和妨碍提供更强大的容错本领。Hystrix具备拥有回退机制和断路器成果的线程和信号断绝,请求缓存和请求打包,昆山软件开发,以及监控和设置等成果。

Dubbo是Alibaba开源的,今朝海内最风行的java rpc框架。

本文先容在spring应用里,怎么把Dubbo和Hystrix团结起来利用。

  • https://github.com/Netflix/Hystrix
  • https://github.com/apache/incubator-dubbo
  • Spring Boot应用

    Demo地点

    生成dubbo集成spring boot的应用

    对付不熟悉dubbo 集成spring boot应用的同学,可以在这里直接生成dubbo + spring boot的工程: http://start.dubbo.io/

    hystrix">设置spring-cloud-starter-netflix-hystrix

    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
    public class ProviderApplication {

    设置Provider端

    在Dubbo的Provider上增加@HystrixCommand设置,这样子挪用就会颠末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端

    对付Consumer端,则可以增加一层method挪用,并在method上设置@HystrixCommand。当挪用堕落时,会走到fallbackMethod = "reliable"的挪用里。

        @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的集成。

    传统Spring Annotation应用

    Demo地点

    传统spring annotation应用的设置其实也很简朴,和spring boot应用差异的是:

    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对Spring的集成是通过Spring AOP来实现的。下面简朴阐明下实现。

    @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里界说了两个注解的AspectJ Pointcut:@HystrixCommand@HystrixCollapser。所有带这两个注解的spring bean城市颠末AOP处理惩罚
    2. @Around AOP处理惩罚函数里,可以看到Hystrix会建设出HystrixInvokable,再通过CommandExecutor来执行

    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里可以发明建设了HystrixCommandAspect
      @Configuration
      public class HystrixCircuitBreakerConfiguration {
      
          @Bean
          public HystrixCommandAspect hystrixCommandAspect() {
              return new HystrixCommandAspect();
          }

    可见spring-cloud-starter-netflix-hystrix实际上也是建设了HystrixCommandAspect来集成Hystrix。