springcloud集成hystrix实现服务降级的大致路由以及配置详解

hystrix的回退机制大概如下图所示:

1:测试hystrix熔断配置:

#设置断路器的状态是false 
ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.circuitBreaker.forceOpen","false");
#设置触发断路器开关的时间:10s        ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.metrics.rollingStats.timeInMilliseconds.",10000);
#设置时间内,请求数达到3次。打开断路器        ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.circuitBreaker.requestVolumeThreshold",3);
#设置时间10s.请求次数3次。失败率达到50%。打开断路器        ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.circuitBreaker.errorThresholdPercentage",50);
#断路器打开后。休眠三秒不在请求实际服务。三秒后再次请求        ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.circuitBreaker.sleepWindowInMilliseconds",3000);
boolean isTimeOut = true;
        for(int i=0;i<20;i++){
            FallbackCommandB fallbackCommand = new FallbackCommandB(isTimeOut);
            fallbackCommand.execute();
            HystrixCommandMetrics.HealthCounts healthCounts = fallbackCommand.getMetrics().getHealthCounts();
            System.out.println("断路器的状态:"+fallbackCommand.isCircuitBreakerOpen()+"总请求的数量:"+healthCounts.getTotalRequests());
            if(fallbackCommand.isCircuitBreakerOpen()){
                //断路器是开的
                isTimeOut = false;
                System.out.println("断路器是开着的,等待休眠结束");
                Thread.sleep(4000);
            }
        }

定义回退:

static class FallbackCommandB extends HystrixCommand<String> {

    private boolean isTimeOut;

    public FallbackCommandB(boolean isTimeOut){
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ExampleGroupB")).andCommandPropertiesDefaults(
                HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(500)
        ));
        this.isTimeOut = isTimeOut;
    }

    @Override
    protected String run() throws Exception {
        System.out.println("执行命令2..");
        if(isTimeOut){
            System.out.println("断路器关着后来再开着。这里把断路器关掉");
            Thread.sleep(800);
        }else{
            System.out.println("断路器关着。如果到达临界阈值就会打开断路器");
            Thread.sleep(300);
        }
        return null;
    }

    protected String getFallback() {
        System.out.println("执行回调2..");
        return "fallback";
    }
}

执行结果:

可以看到第四次请求的时候。断路器状态就打开了。休眠三秒后。再次请求打印:执行命令2.成功了。所以断路器就再次关掉了

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值