微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决Polly 在重试时更改查询字符串

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

我在不同的地方多次使用命名客户端。

这是 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
因此,您需要使用返回 GetAsyncTask<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);
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。