-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpClientManager.cs
More file actions
82 lines (71 loc) · 2.6 KB
/
HttpClientManager.cs
File metadata and controls
82 lines (71 loc) · 2.6 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
70
71
72
73
74
75
76
77
78
79
80
81
82
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace JustLauncher;
/// <summary>
/// Provides a singleton HttpClient instance to avoid socket exhaustion.
/// Creating multiple HttpClient instances can lead to port exhaustion and DNS issues.
/// </summary>
public static class HttpClientManager
{
private static readonly Lazy<HttpClient> _instance = new(() =>
{
var client = new HttpClient
{
Timeout = TimeSpan.FromSeconds(30)
};
// Set default headers
client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36");
return client;
});
/// <summary>
/// Gets the singleton HttpClient instance.
/// </summary>
public static HttpClient Instance => _instance.Value;
public static async Task<HttpResponseMessage> SendWithRetryAsync(
HttpRequestMessage request,
int maxRetries = 3,
int baseDelayMs = 1000)
{
int attempt = 0;
Exception? lastException = null;
while (attempt <= maxRetries)
{
try
{
var response = await Instance.SendAsync(request);
if ((int)response.StatusCode >= 500 && (int)response.StatusCode < 600)
{
if (attempt < maxRetries)
{
var delay = CalculateDelay(attempt, baseDelayMs);
await Task.Delay(delay);
attempt++;
continue;
}
}
return response;
}
catch (HttpRequestException ex) when (attempt < maxRetries)
{
lastException = ex;
var delay = CalculateDelay(attempt, baseDelayMs);
await Task.Delay(delay);
attempt++;
}
catch (TaskCanceledException ex) when (attempt < maxRetries && !ex.CancellationToken.IsCancellationRequested)
{
lastException = ex;
var delay = CalculateDelay(attempt, baseDelayMs);
await Task.Delay(delay);
attempt++;
}
}
throw lastException ?? new HttpRequestException("Request failed after all retry attempts");
}
private static int CalculateDelay(int attempt, int baseDelayMs)
{
var delay = baseDelayMs * Math.Pow(2, attempt);
return (int)Math.Min(delay, 30000);
}
}