Created
March 29, 2021 11:49
-
-
Save brunneus/0971b9960c02c0658a3bdac47f470f4f to your computer and use it in GitHub Desktop.
ResilientHtttpClient
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Flurl.Http; | |
using Polly; | |
using Polly.Retry; | |
using System; | |
using System.Linq; | |
using System.Net; | |
using System.Threading.Tasks; | |
namespace ResilientHttpClient | |
{ | |
public class HttpClient | |
{ | |
public HttpClient() | |
{ | |
} | |
public async Task<T> GetJsonAsync<T>(string url, object headers = null) | |
{ | |
var policy = BuildRetryPolicy(); | |
return await policy.ExecuteAsync(() => url | |
.WithHeaders(headers) | |
.GetJsonAsync<T>() | |
); | |
} | |
private AsyncRetryPolicy BuildRetryPolicy() | |
{ | |
var retryPolicy = Policy | |
.Handle<FlurlHttpException>(IsTransientError) | |
.WaitAndRetryAsync(3, retryAttempt => | |
{ | |
var nextAttemptIn = TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)); | |
Console.WriteLine($"Retry attempt {retryAttempt} to make request. Next try on {nextAttemptIn.TotalSeconds} seconds."); | |
return nextAttemptIn; | |
}); | |
return retryPolicy; | |
} | |
private bool IsTransientError(FlurlHttpException exception) | |
{ | |
int[] httpStatusCodesWorthRetrying = | |
{ | |
(int)HttpStatusCode.RequestTimeout, // 408 | |
(int)HttpStatusCode.BadGateway, // 502 | |
(int)HttpStatusCode.ServiceUnavailable, // 503 | |
(int)HttpStatusCode.GatewayTimeout // 504 | |
}; | |
return exception.StatusCode.HasValue && httpStatusCodesWorthRetrying.Contains(exception.StatusCode.Value); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment