I would like to understand how to implement an optimistic timeout policy with Polly by using the HttpClientFactory
.
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 .AddPolicyHandler(retryPolicy.Wrap(timeoutPolicy))
timeoutPolicy
is the inner policy so it applied for each and every attempt separately retryPolicy
is the outer policy, so it's overarching the timeout policy 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:
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.