[英]Polly Timeout optimistic using HttpClientFactory. How can I use cancellation token?
I would like to understand how to implement an optimistic timeout policy with Polly by using the HttpClientFactory
.我想了解如何使用
HttpClientFactory
与 Polly 实现乐观超时策略。
In the examples on the net, the timeout policy is used when calling asynchronous methods to be able to pass the cancellation token.在网上的示例中,在调用异步方法时使用了超时策略,以便能够传递取消令牌。 But if I set the timeout policy from configure services, as indicated in the guide ), how do I manage the cancellation token?
但是,如果我从配置服务中设置超时策略,如指南中所示),我该如何管理取消令牌?
In example code, from guide linked, I see this:在示例代码中,来自链接的指南,我看到了:
var timeoutPolicy = Policy.TimeoutAsync<HttpResponseMessage>(10); // Timeout for an individual try
serviceCollection.AddHttpClient("GitHub", client =>
{
client.BaseAddress = new Uri("https://api.github.com/");
client.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json");
client.Timeout = TimeSpan.FromSeconds(60); // Overall timeout across all tries
})
.AddPolicyHandler(retryPolicy)
.AddPolicyHandler(timeoutPolicy);
You should chain the retry and timeout policy into a combined policy.您应该将重试和超时策略链接到一个组合策略中。
You have two options:你有两个选择:
Wrap
method Wrap
方法.AddPolicyHandler(retryPolicy.Wrap(timeoutPolicy))
timeoutPolicy
is the inner policy so it applied for each and every attempt separately timeoutPolicy
是内部策略,因此它分别应用于每次尝试retryPolicy
is the outer policy, so it's overarching the timeout policy retryPolicy
是外部策略,因此它覆盖了超时策略PolicyWrap
class PolicyWrap
class.AddPolicyHandler(Policy.Wrap(retryPolicy,timeoutPolicy))
You should be aware that the following two combined policies are very different:您应该知道,以下两种组合策略非常不同:
Policy.Wrap(retryPolicy,timeoutPolicy)
Policy.Wrap(timeoutPolicy, retryPolicy)
Pushing this idea forward you can avoid to set the Timeout
property of HttpClient by defining a global timeout as well:推进这个想法,您可以通过定义全局超时来避免设置 HttpClient 的
Timeout
属性:
var localTimeoutPolicy = Policy.TimeoutAsync<HttpResponseMessage>(10);
var globalTimeoutPolicy = Policy.TimeoutAsync<HttpResponseMessage>(60);
var resilientStrategy = Policy.Wrap(globalTimeoutPolicy, retryPolicy, localTimeoutPolicy);
serviceCollection.AddHttpClient("GitHub", client =>
{
client.BaseAddress = new Uri("https://api.github.com/");
client.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json");
})
.AddPolicyHandler(resilientStrategy);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.