gpt4 book ai didi

c# - Polly 在重试时更改查询字符串

转载 作者:行者123 更新时间:2023-12-04 13:53:29 25 4
gpt4 key购买 nike

我正在使用 .NET 5 并希望使用 Polly 在重试时更改请求的查询字符串。背景 - 我有一个固定的每分钟请求配额,这是我的 IP 地址所允许的。如果超过限制,我会得到一个特定的 4xx 状态代码。在这种情况下,我想添加一个查询字符串参数 ?key=xxx 来处理峰值。计入 API key 的请求成本更高,应该仅在临时达到配额时应用。

我在不同的地方多次使用指定的客户端。

这是Polly适合的场景吗?或者从设计的角度来看,在业务逻辑中处理这个问题是干净的方式吗?然后我需要包装这个逻辑以避免重复自己。

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<string>所以你不能检查响应的 StatusCode .
所以,你需要使用 GetAsync返回 Task<HttpResponseMessage> .

因为请求 uri 是唯一在调用之间发生变化的东西,所以您需要将其作为参数接收:

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 的包装器:

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,然后针对该 url 执行请求。

剩下的就是重试策略本身:

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,则我们退出重试
  • 在所有其他情况下,我们执行重试

用法可能是这样的:

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());

为了完整起见,这里是完整的源代码:

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);
}
}

关于c# - Polly 在重试时更改查询字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66763717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com