天天看點

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"),該屬性用來設定當斷路器打開之後的休眠時間窗。 休眠時間窗結束之後,

  會将斷路器置為 "半開" 狀态,嘗試熔斷的請求指令,如果依然失敗就将斷路器繼續設定為 "打開" 狀态,如果成功就設定為 "關閉" 狀态