天天看點

hystrix熔斷與降級

hystrix熔斷與降級

總結來說就是如果下遊服務挂了,而上遊有多個服務去調用他,那麼上遊的服務就全部挂掉了,這樣會造成雪崩效應,進而使服務大面積的失效。

hystrix熔斷與降級

這就需要在連接配接下遊服務逾時或者異常時會降級走我們定義的方法。或者在一段時間内失敗的比例大于配置,那麼熔斷器會打開,即使正确調用還是會走降級方法。等過一段時間後會嘗試重新調用,如果調用失敗,繼續熔斷,如果成功則可以正常調用。

1.實作

1.修改Application類

修改application中開啟Hystrix。

@EnableFeignClients #開啟feign
@EnableCircuitBreaker #開啟Hystrix      

2.修改application.yml

修改成以下内容。

feign:
  hystrix:
    enabled: true #預設hystrix是不開啟的 需要開啟
ribbon:
  ConnectTimeout: 5000 # 請求連接配接的逾時時間 預設的時間為 1 秒
  ReadTimeout: 5000 # 請求處理的逾時時間
hystrix:
  command:
    default:  #default全局有效,service id指定應用有效
      execution:
        timeout:
          #如果enabled設定為false,則請求逾時交給ribbon控制,為true,則逾時作為熔斷根據
          enabled: true
        isolation:
          strategy: SEMAPHORE
          thread:
            timeoutInMilliseconds: 5000 #斷路器逾時時間,預設1000ms
      circuitBreaker:
        enabled: true
        requestVolumeThreshold: 10 #預設20 ,熔斷的門檻值,如何user服務報錯滿足10次,熔斷器就會打開,就算order之後請求正确的資料也不行。
        sleepWindowInMilliseconds: 8000 #預設5S , 等5S之後熔斷器會處于半開狀态,然後下一次請求的正确和錯誤講決定熔斷器是否真的關閉和是否繼續打開
        errorThresholdPercentage: 0.5      

3.建立UserClientFallBack熔斷類

import org.springframework.stereotype.Component;

@Component
public class UserClientFallBack implements DcClient {

    @Override
    public String consumer() {
        String error= "對不起又是我的錯";
        System.out.println(error);
        return error;
    }

    @Override
    public String consumer2() {
        // TODO Auto-generated method stub
        return null;
    }
}      

依賴于上文 隻要在DcClient 加入fallback =UserClientFallBack.class 然後在調用失敗之後,會直接傳回定義的錯誤,而不會抛出異常。

4.調用

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

@FeignClient(name = "eureka-client",fallback =UserClientFallBack.class )
public interface DcClient {

    @GetMapping("/aaa/dc?dk=3002")
    String consumer();

    @GetMapping("/aaa/dc?dk=3002")
    String consumer2();
}      

相對于ribbon使用不同的請求類型需要不同的方法 feign,通過接口的參數就可以指定。 如

#post請求 入參為user對象
    @PostMapping("/x/x")
    Result getDept(@RequestBody User user);
     

    #get請求 入參為 string 
    @GetMapping("/x/x/{userName}")
    Result getDept(@PathVariable String userName);      

正常調用後。

hystrix熔斷與降級

失敗的調用擷取是連接配接逾時。

hystrix熔斷與降級

繼續閱讀