|
| 1 | +namespace FunctionalLiving.Api.Infrastructure.Modules |
| 2 | +{ |
| 3 | + using System; |
| 4 | + using System.Net.Http; |
| 5 | + using Autofac; |
| 6 | + using Microsoft.Extensions.Configuration; |
| 7 | + using Microsoft.Extensions.DependencyInjection; |
| 8 | + using Microsoft.Extensions.Logging; |
| 9 | + using Microsoft.Net.Http.Headers; |
| 10 | + using Polly; |
| 11 | + |
| 12 | + public class HttpModule : Module |
| 13 | + { |
| 14 | + public static string HttpClientName = "KnxSender"; |
| 15 | + |
| 16 | + public HttpModule( |
| 17 | + IConfiguration configuration, |
| 18 | + IServiceCollection services, |
| 19 | + ILoggerFactory loggerFactory) |
| 20 | + { |
| 21 | + var logger = loggerFactory.CreateLogger<HttpModule>(); |
| 22 | + var retryCount = 5; |
| 23 | + var lifeTimeInMinutes = 20; |
| 24 | + |
| 25 | + // https://github.com/App-vNext/Polly/wiki/Polly-and-HttpClientFactory |
| 26 | + services |
| 27 | + .AddHttpClient(HttpClientName, client => |
| 28 | + { |
| 29 | + client.BaseAddress = configuration.GetValue<Uri>("KnxSender:Endpoint"); |
| 30 | + client.DefaultRequestHeaders.Add(HeaderNames.UserAgent, "FunctionalLiving.Api"); |
| 31 | + }) |
| 32 | + |
| 33 | + .SetHandlerLifetime(TimeSpan.FromMinutes(lifeTimeInMinutes)) |
| 34 | + |
| 35 | + .ConfigurePrimaryHttpMessageHandler(c => |
| 36 | + new HttpClientHandler()) |
| 37 | + |
| 38 | + // HttpRequestException, HTTP 5XX, and HTTP 408 |
| 39 | + .AddTransientHttpErrorPolicy(policyBuilder => policyBuilder |
| 40 | + .WaitAndRetryAsync( |
| 41 | + retryCount, |
| 42 | + retryAttempt => |
| 43 | + { |
| 44 | + var value = Math.Pow(2, retryAttempt) / 4; |
| 45 | + var randomValue = new Random().Next((int)value * 3, (int)value * 5); |
| 46 | + logger?.LogInformation("Retrying after {Seconds} seconds...", randomValue); |
| 47 | + return TimeSpan.FromSeconds(randomValue); |
| 48 | + })); |
| 49 | + } |
| 50 | + } |
| 51 | +} |
0 commit comments