springcloud-Hystrix-服务熔断使用

  服务熔断使用很简单,在可能会出现故障的方法上加上@HystrixCommand,并设置一些属性,如下:

    // 服务熔断
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties ={
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"), //是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"), //请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"), //时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),//失败率达到多少后跳闸
    })
    public String paymentCircuitBreaker(@PathVariable("id") Integer id) {
        if (id < 0) {
            throw new RuntimeException("******id 不能为负数");
        }
        String serialNumber = IdUtil.simpleUUID();
        return Thread.currentThread().getName()+"	"+ "调用成功,流水号:" + serialNumber;
    }

    public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id) {
        return "id 不能负数,请稍后再试,o(╥﹏╥)o id:" + id;
    }

  上面的属性我解释一下:

    1. circuitBreaker.enabled表示 是否开启断路器;

    2. circuitBreaker.requestVolumeThreshold:表示请求次数;

    3. circuitBreaker.sleepWindowInMilliseconds:表示时间窗口期;

    4. circuitBreaker.errorThresholdPercentage:表示请求失败率;

  第一个不用说,就是开启断路器,就可以实现熔断的功能。主要说另外3个,一句话解决:当时间窗口期内,达到 规定的请求次数,就会启动熔断。或者是时间窗口期内请求失败率达到指定值,就会启动熔断。即改方法不能再访问;比如说明的例子:在10s时间内,达到10次请求,则熔断。或者10s内的请求有百分之60是失败的,则启动熔断。

  上面的这些常量值可在 HystrixCommandProperties这个类找到,并且还有其他的常量值。

原文地址:https://www.cnblogs.com/ibcdwx/p/14438828.html