hystrix的使用

hystrix

A service failure in the lower level of services can cause cascading failure all the way up to the user. 
When calls to a particular service is greater than circuitBreaker.requestVolumeThreshold (default: 20 requests) and failue percentage is greater than circuitBreaker.errorThresholdPercentage (default: >50%) in a rolling window defined by metrics.rollingStats.timeInMilliseconds (default: 10 seconds), 
the circuit opens and the call is not made. In cases of error and an open circuit a fallback can be provided by the developer.
  • How to Include Hystrix
    • To include Hystrix in your project use the starter with group org.springframework.cloud and artifact id spring-cloud-starter-hystrix
    • you can see here for more deatils.
  • Default fallback method should not have any parameters except extra one to get execution exception and shouldn't throw any exceptions. Below fallbacks listed in descending order of priority:

    • command fallback defined using fallbackMethod property of @HystrixCommand
    • command default fallback defined using defaultFallback property of @HystrixCommand
    • class default fallback defined using defaultFallback property of @DefaultProperties
  • 对于hystrix究竟是使用thread和semaphore,官网解释如下:

    • thread:请求是在一个单独的线程中执行,当前请求受限与线程池中线程的数量
    • semaphore:请求在当前线程执行,但是当前请求数受限于信号量计数大小。

    对于使用线程池的,有一层额外的保护防止网络超时。所以需要配置超时的,可以采用线程池的方式。
    在你的请求量很大,通常情况下达到每秒上百甚至更多的情况下,单个线程的请求量已经过高,此种情况才使用信号量。这种典型仅仅应用于非网络请求。

  • hystrix断路器说明
    我们看下目前代码中的配置:

    @HystrixCommand(commandProperties = {
          @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000"),
          @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "5"),
          @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "5000000"),
          @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "10"),
          @HystrixProperty(name = "circuitBreaker.forceOpen",value = "false"),
          @HystrixProperty(name = "fallback.enabled",value = "true")
      },
          threadPoolProperties = {
              @HystrixProperty(name = "coreSize", value = "30"),
              @HystrixProperty(name = "maxQueueSize", value = "101"),
              @HystrixProperty(name = "keepAliveTimeMinutes", value = "2"),
              @HystrixProperty(name = "queueSizeRejectionThreshold", value = "15"),
              @HystrixProperty(name = "metrics.rollingStats.numBuckets", value = "10"),
              @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
          })
      public String hystrixTest() {
          log.info("into service......");
          test();
          return "hystrix";
      }
    
    • requestVolumeThreshold = 5,这里配置的是5,也就说时间窗口内最小的请求数达到5,如果是4,哪怕4个请求全部有问题,都不会出发断路器打开。有一点你要注意,你这里配置了fallback,且默认都fallback是开启的,在异常捕获的时候,也没有忽略任何异常,所以每次请求都会进入fallback方法,service方法也会进去。断路器没有打开。
    • 当你超过了5个请求,这个时候,你可以看到断路器开启了。此时fallback方法调用了,但是你进入不了service方法。sleepWindowInMilliseconds这个参数,如果设置了永久,那么你的断路器永远不会关闭。
  • 我们来测试下,超过5个请求后,percentage生效的情况。在第6池开始抛异常,我们看下日志:

2018-08-30 15:35:21.079  INFO 47508 --- [nio-8086-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 18 ms
2018-08-30 15:35:21.103  INFO 47508 --- [nio-8086-exec-1] com.brave.web.Demo                       : into controller...
2018-08-30 15:35:21.318  INFO 47508 --- [x-DemoService-1] com.brave.service.DemoService            : into service......
2018-08-30 15:35:21.318  INFO 47508 --- [x-DemoService-1] com.brave.service.DemoService            : into test method,not throw exception...
2018-08-30 15:35:22.242  INFO 47508 --- [trap-executor-0] c.n.d.s.r.aws.ConfigClusterResolver      : Resolving eureka endpoints via configuration
2018-08-30 15:35:22.295  INFO 47508 --- [nio-8086-exec-3] com.brave.web.Demo                       : into controller...
2018-08-30 15:35:22.297  INFO 47508 --- [x-DemoService-2] com.brave.service.DemoService            : into service......
2018-08-30 15:35:22.297  INFO 47508 --- [x-DemoService-2] com.brave.service.DemoService            : into test method,not throw exception...
2018-08-30 15:35:23.184  INFO 47508 --- [nio-8086-exec-4] com.brave.web.Demo                       : into controller...
2018-08-30 15:35:23.186  INFO 47508 --- [x-DemoService-3] com.brave.service.DemoService            : into service......
2018-08-30 15:35:23.186  INFO 47508 --- [x-DemoService-3] com.brave.service.DemoService            : into test method,not throw exception...
2018-08-30 15:35:24.048  INFO 47508 --- [nio-8086-exec-5] com.brave.web.Demo                       : into controller...
2018-08-30 15:35:24.049  INFO 47508 --- [x-DemoService-4] com.brave.service.DemoService            : into service......
2018-08-30 15:35:24.049  INFO 47508 --- [x-DemoService-4] com.brave.service.DemoService            : into test method,not throw exception...
2018-08-30 15:35:24.863  INFO 47508 --- [nio-8086-exec-6] com.brave.web.Demo                       : into controller...
2018-08-30 15:35:24.865  INFO 47508 --- [x-DemoService-5] com.brave.service.DemoService            : into service......
2018-08-30 15:35:24.865  INFO 47508 --- [x-DemoService-5] com.brave.service.DemoService            : into test method,not throw exception...
2018-08-30 15:35:26.328  INFO 47508 --- [nio-8086-exec-7] com.brave.web.Demo                       : into controller...
2018-08-30 15:35:26.329  INFO 47508 --- [x-DemoService-6] com.brave.service.DemoService            : into service......
2018-08-30 15:35:26.329  INFO 47508 --- [x-DemoService-6] com.brave.service.DemoService            : into test method,not throw exception...
2018-08-30 15:35:26.329  INFO 47508 --- [x-DemoService-6] com.brave.service.DemoService            : throw an exception....
2018-08-30 15:35:27.787  INFO 47508 --- [nio-8086-exec-8] com.brave.web.Demo                       : into controller...
2018-08-30 15:35:29.945  INFO 47508 --- [nio-8086-exec-9] com.brave.web.Demo                       : into controller...
2018-08-30 15:35:32.246  INFO 47508 --- [trap-executor-0] c.n.d.s.r.aws.ConfigClusterResolver      : Resolving eureka endpoints via configuration
2018-08-30 15:35:34.064  INFO 47508 --- [io-8086-exec-10] com.brave.web.Demo                       : into controller...
2018-08-30 15:35:35.770  INFO 47508 --- [nio-8086-exec-2] com.brave.web.Demo                       : into controller...
2018-08-30 15:35:36.971  INFO 47508 --- [nio-8086-exec-1] com.brave.web.Demo                       : into controller...

我们可以看到,在第6哥请求的时候抛了一个异常。第7个请求无法进入,因为断路器开启了。我们设置第percentage是10%。符合预期。如果把这个值放大,会是什么结果?继续看下:

@Service
@DefaultProperties(defaultFallback = "fallback")
@Slf4j
public class DemoService {

    @Autowired DemoClient demoClient;

    public static AtomicInteger number = new AtomicInteger(0);

    public Optional<String> demo() {
        return Optional.ofNullable(demoClient.callDemo());
    }

    @HystrixCommand(commandProperties = {
        @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000"),
        @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "5"),
        @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "5000000"),
        @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "50"),
        @HystrixProperty(name = "circuitBreaker.forceOpen",value = "false"),
        @HystrixProperty(name = "fallback.enabled",value = "true")
    },
        threadPoolProperties = {
            @HystrixProperty(name = "coreSize", value = "30"),
            @HystrixProperty(name = "maxQueueSize", value = "101"),
            @HystrixProperty(name = "keepAliveTimeMinutes", value = "2"),
            @HystrixProperty(name = "queueSizeRejectionThreshold", value = "15"),
            @HystrixProperty(name = "metrics.rollingStats.numBuckets", value = "10"),
            @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
        })
    public String hystrixTest() {
        log.info("into service......");
        test();
        return "hystrix";
    }

    public String fallback() {
        return "fallback";
    }

    public void test() {
        int num = number.addAndGet(1);
        log.info("into test method,not throw exception...");
        if(num>5) {
            log.info("throw an exception....");
            throw new NullPointerException();
        }
    }

}

这里,把percentage调整到了50,我们看下日志:

2018-08-30 15:39:30.690  INFO 47514 --- [nio-8086-exec-1] com.brave.web.Demo                       : into controller...
2018-08-30 15:39:30.892  INFO 47514 --- [x-DemoService-1] com.brave.service.DemoService            : into service......
2018-08-30 15:39:30.892  INFO 47514 --- [x-DemoService-1] com.brave.service.DemoService            : into test method,not throw exception...
2018-08-30 15:39:31.235  INFO 47514 --- [nio-8086-exec-3] com.brave.web.Demo                       : into controller...
2018-08-30 15:39:31.237  INFO 47514 --- [x-DemoService-2] com.brave.service.DemoService            : into service......
2018-08-30 15:39:31.237  INFO 47514 --- [x-DemoService-2] com.brave.service.DemoService            : into test method,not throw exception...
2018-08-30 15:39:31.969  INFO 47514 --- [nio-8086-exec-4] com.brave.web.Demo                       : into controller...
2018-08-30 15:39:31.971  INFO 47514 --- [x-DemoService-3] com.brave.service.DemoService            : into service......
2018-08-30 15:39:31.971  INFO 47514 --- [x-DemoService-3] com.brave.service.DemoService            : into test method,not throw exception...
2018-08-30 15:39:32.507  INFO 47514 --- [trap-executor-0] c.n.d.s.r.aws.ConfigClusterResolver      : Resolving eureka endpoints via configuration
2018-08-30 15:39:32.849  INFO 47514 --- [nio-8086-exec-5] com.brave.web.Demo                       : into controller...
2018-08-30 15:39:32.851  INFO 47514 --- [x-DemoService-4] com.brave.service.DemoService            : into service......
2018-08-30 15:39:32.851  INFO 47514 --- [x-DemoService-4] com.brave.service.DemoService            : into test method,not throw exception...
2018-08-30 15:39:33.947  INFO 47514 --- [nio-8086-exec-6] com.brave.web.Demo                       : into controller...
2018-08-30 15:39:33.949  INFO 47514 --- [x-DemoService-5] com.brave.service.DemoService            : into service......
2018-08-30 15:39:33.949  INFO 47514 --- [x-DemoService-5] com.brave.service.DemoService            : into test method,not throw exception...
2018-08-30 15:39:35.329  INFO 47514 --- [nio-8086-exec-7] com.brave.web.Demo                       : into controller...
2018-08-30 15:39:35.330  INFO 47514 --- [x-DemoService-6] com.brave.service.DemoService            : into service......
2018-08-30 15:39:35.331  INFO 47514 --- [x-DemoService-6] com.brave.service.DemoService            : into test method,not throw exception...
2018-08-30 15:39:35.331  INFO 47514 --- [x-DemoService-6] com.brave.service.DemoService            : throw an exception....
2018-08-30 15:39:37.292  INFO 47514 --- [nio-8086-exec-8] com.brave.web.Demo                       : into controller...
2018-08-30 15:39:37.293  INFO 47514 --- [x-DemoService-7] com.brave.service.DemoService            : into service......
2018-08-30 15:39:37.293  INFO 47514 --- [x-DemoService-7] com.brave.service.DemoService            : into test method,not throw exception...
2018-08-30 15:39:37.293  INFO 47514 --- [x-DemoService-7] com.brave.service.DemoService            : throw an exception....
2018-08-30 15:39:40.416  INFO 47514 --- [nio-8086-exec-9] com.brave.web.Demo                       : into controller...
2018-08-30 15:39:40.417  INFO 47514 --- [x-DemoService-8] com.brave.service.DemoService            : into service......
2018-08-30 15:39:40.418  INFO 47514 --- [x-DemoService-8] com.brave.service.DemoService            : into test method,not throw exception...
2018-08-30 15:39:40.418  INFO 47514 --- [x-DemoService-8] com.brave.service.DemoService            : throw an exception....
2018-08-30 15:39:41.848  INFO 47514 --- [io-8086-exec-10] com.brave.web.Demo                       : into controller...
2018-08-30 15:39:42.512  INFO 47514 --- [trap-executor-0] c.n.d.s.r.aws.ConfigClusterResolver      : Resolving eureka endpoints via configuration
2018-08-30 15:39:47.632  INFO 47514 --- [nio-8086-exec-2] com.brave.web.Demo                       : into controller...
2018-08-30 15:39:48.811  INFO 47514 --- [nio-8086-exec-1] com.brave.web.Demo                       : into controller...

我们看到从第六次开始抛异常,一直到第9次,然后就没有第10次了。>=50%了,断路器打开了。符合预期。
以上大家可以参照我测试第过程,便于大家更清楚的知道断路器的原理。至于scrollwindow和bucket,大家继续再按此方法测试吧,本地模拟不太方便。

  • 我们继续来看下execution.isolation.thread.timeoutInMilliseconds这个参数,我这里设置成5000,也就是说该方法5秒超时,在方法里,sleep了6秒,执行结果看下
2018-08-30 15:53:22.137  INFO 47619 --- [nio-8086-exec-2] com.brave.web.Demo                       : into controller...
2018-08-30 15:53:27.337  INFO 47619 --- [x-DemoService-1] com.brave.service.DemoService            : into service......
2018-08-30 15:53:27.337  INFO 47619 --- [x-DemoService-1] com.brave.service.DemoService            : into test method,not throw exception...
2018-08-30 15:53:27.347  INFO 47619 --- [ HystrixTimer-1] com.brave.service.DemoService            : into fallback....
  • 方法超时6秒,过了6秒继续执行,由于超时了,fallback也执行了。

网上很多杂七杂八的说明,其实都是翻译的官网,很多人看了一知半解,希望这个对大家了解参数有帮助。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,258评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,335评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,225评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,126评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,140评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,098评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,018评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,857评论 0 273
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,298评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,518评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,678评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,400评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,993评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,638评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,801评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,661评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,558评论 2 352

推荐阅读更多精彩内容