使用 Polly 的断路器模式中的超时和重试逻辑

Timeout and Retry Logic in Circuit Breaker pattern using Polly

我正在使用 this 教程通过 HttpClientFactory 和 Polly 实现断路器模式,下面是我根据对教程的理解编写的代码。 RetryHttpRequest class 是使用HttpClient 的class。

  services.AddHttpClient<IRetryHttpRequest, RetryHttpRequest>()
                    .SetHandlerLifetime(TimeSpan.FromSeconds(3))
                    .AddPolicyHandler(GetCircuitBreakerPolicy());

  static IAsyncPolicy<HttpResponseMessage> GetCircuitBreakerPolicy()
        {
            return HttpPolicyExtensions
                .HandleTransientHttpError()
                .CircuitBreakerAsync(5, TimeSpan.FromSeconds(30));
        }
  1. 对于SetHandlerLifetime,这里的生命周期是指每个API请求吗?所以如果我重试 3 次,每次重试应该不会超过 3 秒。有趣的是,默认生命周期是 2 分钟,我认为这太长了。

  2. SetHandlerLifetime(TimeSpan.FromSeconds(3))CircuitBreakerAsync(5, TimeSpan.FromSeconds(30))如何相互关联并相互配合?

SetHandlerLifetime(...)与个别调用超时无关。大约 how long HttpClients provided by HttpClientFactory reuse the same HttpClientHandler, which provides a trade-off between optimising resources and reacting to external DNS changes.

有关通过 HttpClientFactory 应用超时并将其与重试策略相结合的信息,请参阅 Polly's documentation on applying timeout via HttpClientFactory