forked from ThreeMammals/Ocelot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PollyCircuitBreakingDelegatingHandler.cs
53 lines (48 loc) · 1.75 KB
/
PollyCircuitBreakingDelegatingHandler.cs
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
using Ocelot.Logging;
using Ocelot.Provider.Polly.Interfaces;
using Polly;
using Polly.CircuitBreaker;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace Ocelot.Provider.Polly
{
public class PollyCircuitBreakingDelegatingHandler : DelegatingHandler
{
private readonly IPollyQoSProvider _qoSProvider;
private readonly IOcelotLogger _logger;
public PollyCircuitBreakingDelegatingHandler(
IPollyQoSProvider qoSProvider,
IOcelotLoggerFactory loggerFactory)
{
_qoSProvider = qoSProvider;
_logger = loggerFactory.CreateLogger<PollyCircuitBreakingDelegatingHandler>();
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
try
{
var policies = _qoSProvider.CircuitBreaker.Policies;
if (!policies.Any())
{
return await base.SendAsync(request, cancellationToken);
}
IAsyncPolicy policy = policies.Length > 1
? Policy.WrapAsync(policies)
: policies[0];
return await policy.ExecuteAsync(() => base.SendAsync(request, cancellationToken));
}
catch (BrokenCircuitException ex)
{
_logger.LogError("Reached to allowed number of exceptions. Circuit is open", ex);
throw;
}
catch (HttpRequestException ex)
{
_logger.LogError($"Error in {nameof(PollyCircuitBreakingDelegatingHandler)}.{nameof(SendAsync)}", ex);
throw;
}
}
}
}