-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathHttpClientFactory.cs
More file actions
69 lines (63 loc) · 2.78 KB
/
HttpClientFactory.cs
File metadata and controls
69 lines (63 loc) · 2.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using System.Net.Http.Headers;
using Microsoft.Extensions.Http.Resilience;
using Polly;
namespace CreateMatrix;
internal static class HttpClientFactory
{
private static readonly Lazy<HttpClient> s_httpClient = new(CreateHttpClient);
private static readonly Lazy<ResilienceHandler> s_resilienceHandler = new(
CreateResilienceHandler
);
internal static HttpClient GetHttpClient() => s_httpClient.Value;
private static ResilienceHandler GetResilienceHandler() => s_resilienceHandler.Value;
private static ResilienceHandler CreateResilienceHandler() =>
new(
new ResiliencePipelineBuilder<HttpResponseMessage>()
.AddRetry(
new Polly.Retry.RetryStrategyOptions<HttpResponseMessage>
{
MaxRetryAttempts = 3,
BackoffType = DelayBackoffType.Exponential,
UseJitter = true,
Delay = TimeSpan.FromSeconds(1),
MaxDelay = TimeSpan.FromSeconds(30),
ShouldHandle = args =>
ValueTask.FromResult(
args.Outcome.Exception != null
|| args.Outcome.Result is { IsSuccessStatusCode: false }
),
}
)
.AddCircuitBreaker(
new Polly.CircuitBreaker.CircuitBreakerStrategyOptions<HttpResponseMessage>
{
FailureRatio = 0.2,
MinimumThroughput = 10,
SamplingDuration = TimeSpan.FromSeconds(60),
BreakDuration = TimeSpan.FromSeconds(30),
ShouldHandle = args =>
ValueTask.FromResult(
args.Outcome.Exception != null
|| args.Outcome.Result is { IsSuccessStatusCode: false }
),
}
)
.AddTimeout(TimeSpan.FromSeconds(30))
.Build()
)
{
InnerHandler = new SocketsHttpHandler
{
PooledConnectionLifetime = TimeSpan.FromMinutes(15),
PooledConnectionIdleTimeout = TimeSpan.FromMinutes(2),
},
};
private static HttpClient CreateHttpClient()
{
HttpClient httpClient = new(GetResilienceHandler()) { Timeout = TimeSpan.FromSeconds(120) };
httpClient.DefaultRequestHeaders.UserAgent.Add(
new ProductInfoHeaderValue(AssemblyInfo.AppName, AssemblyInfo.InformationalVersion)
);
return httpClient;
}
}