.net 在C#中执行多个API请求的最佳方式是什么?

nqwrtyyt  于 2023-07-01  发布在  .NET
关注(0)|答案(1)|浏览(154)

我工作上有个问题要解决。
我有一个.NET应用程序,我需要向API中的端点发出几个请求,一个接一个,然而,这个API有许多请求问题,并最终返回许多错误。我试着不停地尝试重新发送请求多达5次,但它仍然给出一个错误。
我相信,如果我更好地组织我发送请求的方式,并且间隔稍微长一点,成功的机会就会增加。
你会怎么做你有什么例子吗?
这是我创建的一个例子:(值得一提的是,我有一个列表,一个foreach中有500多个请求,会调用下面的函数)

int numberOfTentatives = 0;
int timeOut = 5000;
Exception lastExpection = new Exception();

ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

Table_Price[] response = new Table_Price[0];
RestClient client = new RestClient(BasePath);
var request = new RestRequest($"api/url", Method.Get);
request.AddQueryParameter("sku", sku);
request.AddHeader("Authorization", token);
request.Timeout = -1;

while (numberOfTentatives < _maxTentatives)
{
    try
    {
        response = client.Get<Table_Price[]>(request);
        return response;
    }
    catch (HttpRequestException ex)
    {
        if (ex.StatusCode == HttpStatusCode.Unauthorized)
        {
            token = $"Bearer {GetToken(_authRequest)}";
        }
        lastExpection = ex;
    }
    catch (Exception ex)
    {
        lastExpection = ex;
    }
    finally
    {
        numberOfTentatives++;
        timeOut += 100;
    }

    Thread.Sleep(timeOut);
}

_CFMContext.Insert_LOG_Error(BrasiliaTime(), $"GetPriceTable({sku})", $"002 - Unable to process api request after 5 attempts : {lastExpection.Message}");
return response;
}
e5njpo68

e5njpo681#

我会使用波利的重试和spicify的状态代码,应处理。然后,您可以使用延迟的指数增加。(如果你愿意)并将其转换为异步。

var response =
     await 
         Policy
             .Handle<HttpRequestException>(ex => CodesToRetry(ex.StatusCode))
             .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)))
             .ExecuteAsync(async () =>
             {
                 return await client.GetAsync<Table_Price[]>(request);
             });
         

public static bool CodesToRetry(System.Net.HttpStatusCode? statusCode)
{
    return
        statusCode is 
            HttpStatusCode.InternalServerError or
            HttpStatusCode.BadGateway or
            HttpStatusCode.ServiceUnavailable or
            HttpStatusCode.GatewayTimeout or
            HttpStatusCode.RequestTimeout or
            HttpStatusCode.TooManyRequests; //TooManyRequests you might want to handle differently. In the response it will tell you how long to wait before retrying.
}

相关问题