Polly重试时更改查询字符串 [英] Polly to change query string on retry

查看:61
本文介绍了Polly重试时更改查询字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用.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< string> ,因此您无法检查响应的StatusCode .
因此,您需要使用 GetAsync 来返回 Task< HttpResponseMessage> .

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,然后针对该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 (因为我们用尽了备用网址),则我们退出重试
  • 如果statusCode在200到299之间,则我们退出重试
  • 如果statusCode在300到400之间或大于500,则我们退出重试
  • 在其他所有情况下,我们都会重试
    • If the GetNewAddressAndPerformRequest returns null 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆