简体   繁体   中英

How to Add Number of Retries in the Polly?

Recently we added Polling mechanism for retry the third party urls.

we Followed this url for retry mechanism polly

Package : Microsoft.Extensions.Http.Polly
version : 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.

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 . Just specify the max number of retries and calculate the time to wait for each retry.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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