zoukankan      html  css  js  c++  java
  • SpringCloud-技术专区-Hystrix-使用指南

    Maven依赖配置

    <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-starter-hystrix</artifactId>
          <version>1.4.3.RELEASE</version>
    </dependency>

    导入配置:

    server:
      port: 11111  
    #default可替换
    hystrix:
      command:
        default:
          execution:
            isolation:
              #线程池隔离还是信号量隔离 默认是THREAD 信号量是SEMAPHORE
              strategy: THREAD
              semaphore:
                #使用信号量隔离时,支持的最大并发数 默认10
                maxConcurrentRequests: 10
              thread:
                #command的执行的超时时间 默认是1000
                timeoutInMilliseconds: 1000
                #HystrixCommand.run()执行超时时是否被打断 默认true
                interruptOnTimeout: true
                #HystrixCommand.run()被取消时是否被打断 默认false
                interruptOnCancel: false
            timeout:
              #command执行时间超时是否抛异常 默认是true
              enabled: true
            fallback:
              #当执行失败或者请求被拒绝,是否会尝试调用hystrixCommand.getFallback()
              enabled: true
              isolation:
                semaphore:
                  #如果并发数达到该设置值,请求会被拒绝和抛出异常并且fallback不会被调用 默认10
                  maxConcurrentRequests: 10
          circuitBreaker:
            #用来跟踪熔断器的健康性,如果未达标则让request短路 默认true
            enabled: true
            #一个rolling window内最小的请求数。如果设为20,那么当一个rolling window的时间内
            #(比如说1个rolling window是10秒)收到19个请求,即使19个请求都失败,也不会触发circuit break。默认20
            requestVolumeThreshold: 5
            # 触发短路的时间值,当该值设为5000时,则当触发circuit break后的5000毫秒内
            #都会拒绝request,也就是5000毫秒后才会关闭circuit,放部分请求过去。默认5000
            sleepWindowInMilliseconds: 5000
            #错误比率阀值,如果错误率>=该值,circuit会被打开,并短路所有请求触发fallback。默认50
            errorThresholdPercentage: 50
            #强制打开熔断器,如果打开这个开关,那么拒绝所有request,默认false
            forceOpen: false
            #强制关闭熔断器 如果这个开关打开,circuit将一直关闭且忽略
            forceClosed: false
          metrics:
            rollingStats:
              #设置统计的时间窗口值的,毫秒值,circuit break 的打开会根据1个rolling window的统计来计算。若rolling window被设为10000毫秒,
              #则rolling window会被分成n个buckets,每个bucket包含success,failure,timeout,rejection的次数的统计信息。默认10000
              timeInMilliseconds: 10000
              #设置一个rolling window被划分的数量,若numBuckets=10,rolling window=10000,
              #那么一个bucket的时间即1秒。必须符合rolling window % numberBuckets == 0。默认10
              numBuckets: 10
            rollingPercentile:
              #执行时是否enable指标的计算和跟踪,默认true
              enabled: true
              #设置rolling percentile window的时间,默认60000
              timeInMilliseconds: 60000
              #设置rolling percentile window的numberBuckets。逻辑同上。默认6
              numBuckets: 6
              #如果bucket size=100,window=10s,若这10s里有500次执行,
              #只有最后100次执行会被统计到bucket里去。增加该值会增加内存开销以及排序的开销。默认100
              bucketSize: 100
            healthSnapshot:
              #记录health 快照(用来统计成功和错误绿)的间隔,默认500ms
              intervalInMilliseconds: 500
          requestCache:
            #默认true,需要重载getCacheKey(),返回null时不缓存
            enabled: true
          requestLog:
            #记录日志到HystrixRequestLog,默认true
            enabled: true
      collapser:
        default:
          #单次批处理的最大请求数,达到该数量触发批处理,默认Integer.MAX_VALUE
          maxRequestsInBatch: 2147483647
          #触发批处理的延迟,也可以为创建批处理的时间+该值,默认10
          timerDelayInMilliseconds: 10
          requestCache:
            #是否对HystrixCollapser.execute() and HystrixCollapser.queue()的cache,默认true
            enabled: true
      threadpool:
        default:
          #并发执行的最大线程数,默认10
          coreSize: 10
          #Since 1.5.9 能正常运行command的最大支付并发数
          maximumSize: 10
          #BlockingQueue的最大队列数,当设为-1,会使用SynchronousQueue,值为正时使用LinkedBlcokingQueue。
          #该设置只会在初始化时有效,之后不能修改threadpool的queue size,除非reinitialising thread executor。
          #默认-1。
          maxQueueSize: -1
          #即使maxQueueSize没有达到,达到queueSizeRejectionThreshold该值后,请求也会被拒绝。
          #因为maxQueueSize不能被动态修改,这个参数将允许我们动态设置该值。if maxQueueSize == -1,该字段将不起作用
          queueSizeRejectionThreshold: 5
          #Since 1.5.9 该属性使maximumSize生效,值须大于等于coreSize,当设置coreSize小于maximumSize
          allowMaximumSizeToDivergeFromCoreSize: false
          #如果corePoolSize和maxPoolSize设成一样(默认实现)该设置无效。
          #如果通过plugin(https://github.com/Netflix/Hystrix/wiki/Plugins)使用自定义实现,该设置才有用,默认1.
          keepAliveTimeMinutes: 1
          metrics:
            rollingStats:
              #线程池统计指标的时间,默认10000
              timeInMilliseconds: 10000
              #将rolling window划分为n个buckets,默认10
              numBuckets: 10

        其中execution:isolation:strategy有些区别:

     资源隔离

           就是多个依赖服务的调用分别隔离到各自自己的资源池内。避免说对一个依赖服务的调用,因为依赖服务接口调用的失败或者延迟,导致所有的线程资源都全部耗费在这个接口上。一旦某个服务的线程资源全部耗尽可能导致服务的崩溃,甚至故障蔓延。    

    资源隔离的方法       

           信号量semaphore,最多能容纳10个请求。一旦超过10个信号量最大容量,那么就会拒绝其他请求。

    信号量与线程池资源隔离的区别:

           线程池隔离技术并非控制tomcat等web容器的线程。更准确的说就是控制tomcat线程的执行。tomcat接到请求之后会调用hystrix线程池的线程去执行。当线程池满了之后会调用fallback降级。
      tomcat其他的线程不会卡死,快速返回,然后可以支撑其他事情。同时hystrix处理timeout超时问题。
           信号量隔离只是一个关卡,通过我的关卡的线程是固定的。容量满了之后。fallback降级。
            区别:线程池隔离技术是用自己的线程去执行调用。信号量是直接让tomcat线程去执行依赖服务。

    上图是默认的配置,我们可以对自己的配置进行分组:

              针对不同的组在配置文件里面加上不同的配置就好了,在@MyCommand注解里面指定group为abc就行;其他的配置也是这个规则,还有默认的配置是default;这样可以把一个组的配置独立出来,便于配置,而且开发者也会方便很多,代码简洁;

    下面是代码:

    package cn.chinotan.controller;
    
    import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
    import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    /**
     * @program: test
     * @description: hystrix控制器
     * @author: xingcheng
     * @create: 2018-11-03 19:27
     **/
    @RestController
    @RequestMapping("/hystrix")
    public class HystrixController {
    
        @HystrixCommand(fallbackMethod = "helloFallback")
        @RequestMapping("/sayHello")
        public String sayHello(String name, Integer time) {
            try {
                Thread.sleep(time);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "Hello, " + name;
        }
    
        @HystrixCommand(fallbackMethod = "hiFallback")
        @RequestMapping("/sayHi")
        public String sayHi(String name) {
            if (StringUtils.isBlank(name)) {
                throw new RuntimeException("name不能为空");
            }
            return "Good morning, " + name;
        }
    
        /**
         * fallback
         */
        public String helloFallback(String name, Integer time) {
            System.out.println("helloFallback: " + name);
            return "helloFallback" + name;
        }
    
        /**
         * fallback
         */
        public String hiFallback(String name) {
            System.out.println("hiFallback: " + name);
            return "hiFallback" + name;
        }
    }
    
    
    package cn.chinotan.config;
    
    import com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect;
    import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
    import org.springframework.boot.web.servlet.ServletRegistrationBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    /**
     * @program: test
     * @description: HystrixConfig
     * @author: xingcheng
     **/
    @Configuration
    public class HystrixConfig {
    
        /**
         * 用来拦截处理HystrixCommand注解
         * @return
         */
        @Bean
        public HystrixCommandAspect hystrixAspect() {
            return new HystrixCommandAspect();
        }
    
        /**
         * 用来像监控中心Dashboard发送stream信息
         * @return
         */
        @Bean
        public ServletRegistrationBean hystrixMetricsStreamServlet() {
            ServletRegistrationBean registration = new ServletRegistrationBean(new HystrixMetricsStreamServlet());
            registration.addUrlMappings("/hystrix.stream");
            return registration;
        }
        
    }
    

    总结

    • 雪崩效应原因:硬件故障、硬件故障、程序Bug、重试加大流量、用户大量请求。
    • 雪崩的对策:限流、改进缓存模式(缓存预加载、同步调用改异步)、自动扩容、降级。
    • Hystrix设计原则:
      • 资源隔离:Hystrix通过将每个依赖服务分配独立的线程池进行资源隔离, 从而避免服务雪崩。
      • 熔断开关:服务的健康状况 = 请求失败数 / 请求总数,通过阈值设定和滑动窗口控制开关。
      • 命令模式:通过继承 HystrixCommand 来包装服务调用逻辑。
    极限就是为了超越而存在的
  • 相关阅读:
    JMeter使用正则表达式提取相应信息
    Python的configparser生成配置文件,以及相关操作
    Python函数主要的作用
    Python函数传参位置关系总结
    Python中的作用域
    Python高阶函数解析
    Python中set集合的增加,update和add的区别
    Oracle 11g服务详细介绍及哪些服务是必须开启的?
    javacc jjtree 写法 以及 jj写法 基本语法 以及应用
    Python 3.3 try catch所有的错误Error,不包括Exception。关键在于 sys.exc_info()
  • 原文地址:https://www.cnblogs.com/liboware/p/11908727.html
Copyright © 2011-2022 走看看