Polly 在重试时更改查询字符串 [英] Polly to change query string on retry
问题描述
我正在使用 .NET 5 并希望使用 Polly 在重试时更改请求的查询字符串.背景 - 我有一个固定的每分钟请求配额,这是我的 IP 地址允许的.如果超过限制,我会收到一个特定的 4xx 状态代码.在这种情况下,我想添加一个查询字符串参数 ?key=xxx
来处理峰值.计入 API 密钥的请求成本更高,并且仅应在临时达到配额时应用.
I'm using .NET 5 and want to use Polly to change the query string of a request on a retry.
Background - I have a fixed quota of requests per minute which is allowed from my IP address. If I exceed the limit, I get a specific 4xx status code. In this case I want to add a query string argument ?key=xxx
to handle peaks. The requests counting towards the API key are more expensive and should only apply if reached the quota temporary.
我在不同的地方多次使用命名客户端.
I use the named client many times in different places.
这是 Polly 适合的场景吗?或者从设计的角度来看,在业务逻辑中处理这个问题是干净的方式吗?然后我需要包装这个逻辑以避免重复自己.
Is this a scenario for which Polly is suitable? Or from a design perspective, is handling this in business logic the clean way? Then I need to wrap this logic to avoid repeating myself.
var response = await client.GetStringAsync("https://test.com");
if (!response.IsSuccessStatusCode && response.StatusCode == 4xx)
response = await client.GetStringAsync("https://test.com?key=XXX")
// continue with regular workflow - handling errors or process response
推荐答案
GetStringAsync
返回一个 Task
所以你不能检查响应的 状态码
.
因此,您需要使用 GetAsync
返回一个 Task
.
The GetStringAsync
returns a Task<string>
so you can't examine the reponse's StatusCode
.
So, you need to use GetAsync
which returns a Task<HttpResponseMessage>
.
因为请求 uri 是唯一在调用之间发生变化的东西,这就是您需要将其作为参数接收的原因:
Because the request uri is the only thing which is changing between the calls that's why you need to receive that as a parameter:
private static HttpClient client = new HttpClient(); //or use IHttpClientFactory
static async Task<HttpResponseMessage> PerformRequest(string uri)
{
Console.WriteLine(uri);
return await client.GetAsync(uri);
}
为了有一个可以由重试策略执行的无参数操作,我们需要一个地址迭代器和一个围绕 PerformRequest
的包装器:
In order to have a parameter-less action which can be performed by the retry policy we need an address iterator and a wrapper around the PerformRequest
:
static IEnumerable<string> GetAddresses()
{
yield return "https://test.com";
yield return "https://test.com?key=XXX";
...
}
private static readonly IEnumerator<string> UrlIterator = GetAddresses().GetEnumerator();
static async Task<HttpResponseMessage> GetNewAddressAndPerformRequest()
{
if (UrlIterator.MoveNext())
return await PerformRequest(UrlIterator.Current);
return null;
}
每次当您调用 GetNewAddressAndPerformRequest
时,它都会检索下一个回退 url,然后针对它执行请求.
Each time when you call the GetNewAddressAndPerformRequest
it retrieves the next fallback url and then executes the request against that.
剩下的是重试策略本身:
What's left is the retry policy itself:
var retryPolicyForNotSuccessAnd4xx = Policy
.HandleResult<HttpResponseMessage>(response => response != null && !response.IsSuccessStatusCode)
.OrResult(response => response != null && (int)response.StatusCode > 400 && (int)response.StatusCode < 500)
.WaitAndRetryForeverAsync(_ => TimeSpan.FromSeconds(1));
- 如果
GetNewAddressAndPerformRequest
返回null
因为我们已经用完了回退 url,那么我们退出重试 - 如果 statusCode 介于 200 和 299 之间,则退出重试
- 如果 statusCode 介于 300 和 400 之间或大于 500,则我们退出重试
- 在其他所有情况下,我们都会重试
- If the
GetNewAddressAndPerformRequest
returnsnull
because we have run out of fallback urls then we exit from the retry - If the statusCode is between 200 and 299 then we exit from the retry
- If the statusCode is between 300 and 400 or greater than 500 then we exit from the retry
- In every other case we perform a retry
用法可能如下所示:
var response = await retryPolicyForNotSuccessAnd4xx.ExecuteAsync(async () => await GetNewAddressAndPerformRequest());
if (response == null)
{
Console.WriteLine("All requests failed");
Environment.Exit(1);
}
Console.WriteLine(await response.Content.ReadAsStringAsync());
为了完整起见,这里是完整的源代码:
For the sake of completeness here is the full source code:
class Program
{
private static HttpClient client = new HttpClient();
static async Task Main(string[] args)
{
var retryPolicyForNotSuccessAnd4xx = Policy
.HandleResult<HttpResponseMessage>(response => response != null && !response.IsSuccessStatusCode)
.OrResult(response => response != null && (int)response.StatusCode > 400 && (int)response.StatusCode < 500)
.WaitAndRetryForeverAsync(_ => TimeSpan.FromSeconds(1));
var response = await retryPolicyForNotSuccessAnd4xx.ExecuteAsync(async () => await GetNewAddressAndPerformRequest());
if (response == null)
{
Console.WriteLine("All requests failed");
Environment.Exit(1);
}
Console.WriteLine(await response.Content.ReadAsStringAsync());
}
static IEnumerable<string> GetAddresses()
{
yield return "https://test.com";
yield return "https://test.com?key=XXX";
}
private static readonly IEnumerator<string> UrlIterator = GetAddresses().GetEnumerator();
static async Task<HttpResponseMessage> GetNewAddressAndPerformRequest()
=> UrlIterator.MoveNext() ? await PerformRequest(UrlIterator.Current) : null;
static async Task<HttpResponseMessage> PerformRequest(string uri)
{
Console.WriteLine(uri);
return await client.GetAsync(uri);
}
}
这篇关于Polly 在重试时更改查询字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!