简体   繁体   English

如何在 Polly 中添加重试次数?

[英]How to Add Number of Retries in the Polly?

Recently we added Polling mechanism for retry the third party urls.最近我们添加了轮询机制来重试第三方 url。

we Followed this url for retry mechanism polly我们按照这个 url 进行重试机制polly

Package : Microsoft.Extensions.Http.Polly包:Microsoft.Extensions.Http.Polly
version : 2.1.1版本:2.1.1

Here is our Code :这是我们的代码:

public async Task<HttpResponseMessage> RetryAPI(string request, string apiName)
        {
            var content = new HttpResponseMessage();            
            var httpStatusCodesWorthRetrying = ["500","502","503","504"];
            var httpStatusMessagesWorthRetrying = ["InternalServerError","BadGateway","ServiceUnavailable","GatewayTimeout"];
            var retrytimes = [1,2,3];
            var retrysecs = [2,4,6];
            List<TimeSpan> intervals = new List<TimeSpan>();

            foreach (var intervaltime in retrysecs)
                intervals.Add(TimeSpan.FromSeconds(Convert.ToDouble(intervaltime)));
 
            content = await Policy
            .HandleResult<HttpResponseMessage>(r => (httpStatusCodesWorthRetrying.Contains(((int)r.StatusCode).ToString())) || (httpStatusMessagesWorthRetrying.Contains((r.StatusCode).ToString())))
            .WaitAndRetryAsync(intervals)
            .ExecuteAsync(async () => await ApiCall(request, apiName));

            return content;
        }

we got new requirement that we should send no of retry to the Policy Class.我们得到了新的要求,即我们不应该向策略类发送重试

How to send No.of Retry( retrytimes ) to the WaitAndRetryAsync Method.如何节数重试(retrytimes)发送到WaitAndRetryAsync方法。

Thanks in advance!提前致谢!

From the documentation :文档

// Retry a specified number of times, using a function to 
// calculate the duration to wait between retries based on 
// the current retry attempt (allows for exponential backoff)
// In this case will wait for
//  2 ^ 1 = 2 seconds then
//  2 ^ 2 = 4 seconds then
//  2 ^ 3 = 8 seconds then
//  2 ^ 4 = 16 seconds then
//  2 ^ 5 = 32 seconds
Policy
  .Handle<SomeExceptionType>()
  .WaitAndRetry(5, retryAttempt => 
    TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)) 
  );

So for your example:所以对于你的例子:

// This will retry 3 times, like you current example
// by waiting 2, 4 and 6 seconds respectively.
content = await Policy
    .HandleResult<HttpResponseMessage>(r =>
        (httpStatusCodesWorthRetrying.Contains(((int)r.StatusCode).ToString()))
        || (httpStatusMessagesWorthRetrying.Contains((r.StatusCode).ToString())))
    .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(retryAttempt * 2))
    .ExecuteAsync(async () => await ApiCall(request, apiName));

You don't need to pass retrytimes .您不需要通过retrytimes Just specify the max number of retries and calculate the time to wait for each retry.只需指定最大重试次数并计算每次重试的等待时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM