forked from redhat-dotnet-msa/circuitbreaker_console_app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
executable file
·76 lines (69 loc) · 2.56 KB
/
Program.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System.Diagnostics;
using System;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Builder;
using System.Net.Http;
using Polly;
using Polly.Timeout;
using Polly.CircuitBreaker;
namespace circuitbreaker_console_app
{
public class Program
{
public static void Main(string[] args)
{
RunAsync().Wait();
}
static async Task RunAsync()
{
CancellationToken cancellationToken = new CancellationToken();
double timeoutvalue = 200;
TimeoutStrategy timeoutStrategy = TimeoutStrategy.Pessimistic;
var client = new HttpClient();
var timeoutPolicy = Policy
.TimeoutAsync(TimeSpan.FromMilliseconds(timeoutvalue), timeoutStrategy);
var circuitBreakerPolicy = Policy
.Handle<Exception>()
.Or<TimeoutRejectedException>()
.Or<TimeoutException>()
.CircuitBreakerAsync(
exceptionsAllowedBeforeBreaking: 4,
durationOfBreak: TimeSpan.FromSeconds(8),
onBreak: (ex, breakDelay) =>
{
Console.WriteLine(".Breaker logging: Breaking the circuit for " + breakDelay.TotalMilliseconds + "ms!");
Console.WriteLine("...due to: " + ex.Message);
},
onReset: () => Console.WriteLine(".Breaker logging: Call ok! Closed the circuit again."),
onHalfOpen: () => Console.WriteLine(".Breaker logging: Half-open; next call is a trial.")
);
int i = 0;
// Do the following until a key is pressed
while (!Console.KeyAvailable && !cancellationToken.IsCancellationRequested)
{
i++;
try
{
// Retry the following call according to the policy - 3 times.
string msg = await Policy.WrapAsync(circuitBreakerPolicy, timeoutPolicy).ExecuteAsync<String>(() =>
{
return client.GetStringAsync("http://10.1.2.2:5000/greeting");
});
Console.WriteLine("Request " + i + ": " + msg);
}
catch (BrokenCircuitException b) {
Console.WriteLine("Request " + i + " failed with: " + b.GetType().Name);
}
catch (Exception e)
{
Console.WriteLine("Request " + i + " eventually failed with: " + e.Message);
}
// Wait half second
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
};
}
}
}