Skip to content

Instantly share code, notes, and snippets.

@brunneus
Created March 29, 2021 11:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save brunneus/0971b9960c02c0658a3bdac47f470f4f to your computer and use it in GitHub Desktop.
Save brunneus/0971b9960c02c0658a3bdac47f470f4f to your computer and use it in GitHub Desktop.
ResilientHtttpClient
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