天天看点

hystrix服务熔断(1)

断路器一句话就是家里的保险丝

熔断机制概述

熔断机制是应对雪崩效应的一种微服务链路保护机制。当扇出链路的某个微服务出错不可用或者响应时间太长时,

会进行服务的降级,进而熔断该节点微服务的调用,快速返回错误的响应信息。

当检测到该节点微服务调用响应正常后,恢复调用链路。

在Spring Cloud框架里,熔断机制通过Hystrix实现。Hystrix会监控微服务间调用的状况,

当失败的调用到一定阈值,缺省是5秒内20次调用失败,就会启动熔断机制。熔断机制的注解是@HystrixCommand。

hystrix服务熔断(1)

熔断类型 

 熔断打开

请求不再进行调用当前服务,内部设置时钟一般为MTTR(平均故障处理时间),当打开时长达到所设时钟则进入半熔断状态

熔断关闭

熔断关闭不会对服务进行熔断

熔断半开

部分请求根据规则调用当前服务,如果请求成功且符合规则则认为当前服务恢复正常,关闭熔断

 大神论文学习地址

https://martinfowler.com/bliki/CircuitBreaker.html      

 代码演示

启动类记得加:

@EnableHystrix      

业务代码

@GetMapping("/payment/circuit/{id}")
public String paymentCircuitBreaker(@PathVariable("id") Integer id)
{
    String result = paymentService.paymentCircuitBreaker(id);
    log.info("****result: "+result);
    return result;
}      
通过 调用paymentService类中的paymentCircuitBreaker(id)方法,具体如下
//=========服务熔断
@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()+"\t"+"调用成功,流水号: " + serialNumber;
}
public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id)
{
    return "id 不能负数,请稍后再试,/(ㄒoㄒ)/~~   id: " +id;
}      

 @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"),

})

 @HystrixCommand:需要进行熔断或者降级处理的业务处理方法的标注注解

fallbackMethod:发生熔断的时候需要调用的方法

@HystrixProperty:相关参数的设置

@HystrixProperty(name = "circuitBreaker.enabled",value = "true"),name ="circuitBreaker.enabled",value = "true",是否启用断路器

@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),  

该属性用来设置在滚动时间窗中,断路器熔断的最小请求数。例如,默认该值为 20 的时候,如果滚动时间窗(默认10秒)内仅收到了19个请求, 即使这19个请求都失败了,断路器也不会打开。

  @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),该属性用来设置当断路器打开之后的休眠时间窗。 休眠时间窗结束之后,

  会将断路器置为 "半开" 状态,尝试熔断的请求命令,如果依然失败就将断路器继续设置为 "打开" 状态,如果成功就设置为 "关闭" 状态