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

时间:2019-11-13 22:56:30

标签: c# timeout httpclient circuit-breaker polly

我正在使用this教程通过HttpClientFactory和Polly实现Circuit Breaker模式,这是基于我对教程的理解而编写的以下代码。 fname = "test.mp4" with open(fname, "rb") as f: r = requests.post( url, files=[ ("data", (os.path.basename(fname), f, "video/mp4")), ] ) print(r.status_code) print(r.text) 类是使用HttpClient的类。

RetryHttpRequest
  1. 对于 services.AddHttpClient<IRetryHttpRequest, RetryHttpRequest>() .SetHandlerLifetime(TimeSpan.FromSeconds(3)) .AddPolicyHandler(GetCircuitBreakerPolicy()); static IAsyncPolicy<HttpResponseMessage> GetCircuitBreakerPolicy() { return HttpPolicyExtensions .HandleTransientHttpError() .CircuitBreakerAsync(5, TimeSpan.FromSeconds(30)); } ,此处的生存期是否意味着每个API请求?因此,如果我重试3次,则每次重试应不超过3秒。有趣的是,默认生存期是2分钟,我认为这太长了。

  2. SetHandlerLifetimeSetHandlerLifetime(TimeSpan.FromSeconds(3))如何相互关联并相互配合?

1 个答案:

答案 0 :(得分:1)

SetHandlerLifetime(...)与单个呼叫的超时无关。关于how long HttpClients provided by HttpClientFactory reuse the same HttpClientHandler,它提供了trade-off between optimising resources and reacting to external DNS changes

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