.NET Core + Spring Cloud:熔斷降級

在微服務架構下,服務之間彼此隔離,服務之間的調用通過網絡請求,在衆多服務中,可能因爲網絡或服務本身的原因引起某些接口異常是很常見的現象,接口超時或報錯在實際情況下偶發也屬正常,但如果短時間內不斷的出現並積壓,就可能引起服務崩潰。

Hystrix 是 Spring Cloud 中的核心組件,它提供了熔斷、隔離、降級、請求緩存、監控等功能,能夠在依賴的服務出現問題時保證系統依然可用。

如下圖,當 Dependenccy I 發生故障時,通過 Hystrix 的配置策略決定作出何種響應,如限流拒絕請求、接口異常超過閾值快速返回失敗、接口超時發起重試等。

創建 .NET Core Hystrix 服務

基於 .NET Core + Spring Cloud:API 網關 的所有服務,對 client-service 進行熔斷降級測試。

修改 client-service :

  1. Nuget 添加引用,MetricsEventsCore 主要對 stream 的監測使用(後面會說明)

    Install-Package Steeltoe.CircuitBreaker.HystrixCore
    Install-Package Steeltoe.CircuitBreaker.Hystrix.MetricsEventsCore
    
  2. 創建 HystrixCommand

    之前是通過構造函數注入BaseService ,直接調用 BaseService 中的方法,現在需要對 BaseService 中的方法進行熔斷降級,就需要定義HystrixCommand(本質上是一個代理模式),通過重寫 HystrixCommand 的 RunAsync 來調用 _baseService.GetValueAsync()。使用 Steeltoe Hystrix 時,需要爲每個方法創建一個 HystrixCommand,這個實在有些繁瑣,希望後續版本會優化。IHystrixCommandOptions 爲 Command 的策略配置參數,未設置則使用默認值,可在配置文件進行設置覆蓋,參考:Command Settings

    public class GetValueCommand : HystrixCommand<string>
    {
        private readonly IBaseService _baseService;
    
        public GetValueCommand(IHystrixCommandOptions options,
            IBaseService baseService) : base(options)
        {
            _baseService = baseService;
        }
    
        public async Task<string> GetValueAsync()
        {
            return await ExecuteAsync();
        }
    
        protected override async Task<string> RunAsync()
        {
            return await _baseService.GetValueAsync();
        }
    
        /// <summary>
        /// 熔斷降級執行方法
        /// </summary>
        /// <returns></returns>
        protected override async Task<string> RunFallbackAsync()
        {
            return await Task.FromResult("調用 GetValueAsync 接口異常,服務異常,請稍候再試");
        }
    }
    
  3. Startup.cs ConfigureServices 方法中添加:

    // Add Steeltoe Hystrix Command
    services.AddHystrixCommand<GetValueCommand>("base-service", Configuration);
    
    // Add Hystrix Metrics to container
    services.AddHystrixMetricsStream(Configuration);
    
  4. Startup.cs Configure方法中添加:

     // Start Hystrix metrics stream service
     app.UseHystrixMetricsStream();
    

搭建 Hystrix Dashboard

在進行測試之前,爲了更加形象查看效果,我們藉助 Hystrix Dashboard 來監控。

  1. 在 IntelliJ IDEA 中新建項目,選 Spring Initializr 完成項目創建

  2. 在 pom.xml 添加 hystrix-dashboard 和 eureka-client 的依賴,我們將會把 Hystrix Dashboard 註冊到 Eureka Server

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
    </dependency>
    
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    
  3. 在啓動類上添加 EnableHystrixDashboard 註解

    @EnableHystrixDashboard
    @SpringBootApplication
    public class EurekaServiceApplication {
        public static void main(String[] args) {
            SpringApplication.run(EurekaServiceApplication.class, args);
        }
    }
    
  4. 修改 application.yml 配置文件

    spring:
      application:
        name: hystrix-dashboard-service
    
    server:
      port: 6500
    
    eureka:
      instance:
        hostname: server1
      client:
        service-url:
          defaultZone: http://server1:8001/eureka/,http://server2:8002/eureka/,http://server3:8003/eureka/
    
  5. 啓動服務,訪問:http://server1:8001/,可以發現 Hystrix Dashboard 已在 6500 端口啓動

  6. 訪問:http://server1:6500/hystrix

    這時我們需要輸入 client-service(http://server1:6001/hystrix/hystrix.stream) 的 stream 地址進行監測。

測試

正常情況請求 http://server1:5555/client-service/api/values/getvalue 接口沒問題:

我們可以針對某個 HystrixCommand 配置參數覆蓋默認值,在 appsettings.json 添加如下配置,GetValueCommand 執行超時時間爲 10ms,所以會存在偶發的 Timeout ,Timeout 時會返回 Fallback 方法結果:

  "hystrix": {
    "command": {
      "GetValueCommand": {
        "execution": {
          "isolation": {
            "thread": {
              "timeoutInMilliseconds": 10
            }
          }
        }
      }
    }
  }

當 Fallback 次數觸發了 熔斷閾值,會進入 Short-Circuited 狀態:

當把 base-service 服務全部殺掉,請求會進入 Failure 狀態:

Steeltoe 的 Circuit Breaker 還支持 Request Cache、Request Logging、Thread Pool 等,更多請參考 官方文檔

參考鏈接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章