This repository has been archived by the owner on Jul 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Program.cs
87 lines (81 loc) · 3.03 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
77
78
79
80
81
82
83
84
85
86
87
using Polly;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OpenSourceTools.Polly.Demo
{
class Program
{
public static int random = 10;
static void Main(string[] args)
{
try
{
//Retry();
//WaitandRetryForeverUntilSuccess();
//WaitAndRetry();
var circuitBreaker = Policy.Handle<DivideByZeroException>()
.CircuitBreaker(3, TimeSpan.FromMinutes(1))
.Execute(() => DivideByZero(10));
}
catch (Exception ex)
{
Console.WriteLine($"失败信息:{ex.Message}");
}
}
/// <summary>
/// Retry
/// </summary>
public static void Retry()
{
var retry = Policy
.Handle<DivideByZeroException>()
.Retry(3, (exception, retryCount) =>
{
Console.WriteLine($"执行异常,重试次数:{retryCount},【异常来自:{exception.GetType().Name}】.");
});
retry.Execute(() => { DivideByZero(random); });
}
/// <summary>
/// Wait and retry
/// </summary>
public static void WaitAndRetry()
{
var retry = Policy
.Handle<DivideByZeroException>()
.WaitAndRetry(5, retryAttempt => TimeSpan.FromSeconds(Math.Pow(1, retryAttempt)),
(exception, timespan, retryCount, context) =>
{
Console.WriteLine($"重试,[当前随机数为{random}] [retrycount{retryCount}] [异常来自:{exception.GetType().Name}] [{timespan}]");
random = new Random().Next(10, 50);
if (random == 25)
Console.WriteLine($"成功,随机数为{random}");
});
retry.Execute(() => DivideByZero(random));
}
/// <summary>
/// Wait and retry forever (until succeeds)
/// </summary>
public static void WaitandRetryForeverUntilSuccess()
{
var retryForever = Policy
.Handle<DivideByZeroException>()
.WaitAndRetryForever(retryAttempt => TimeSpan.FromSeconds(Math.Pow(1, retryAttempt)), (exception, timespan) =>
{
Console.WriteLine($"重试,[当前随机数为{random}][异常来自:{exception.GetType().Name}] [{timespan}]");
random = new Random().Next(10, 50);
if (random == 25)
Console.WriteLine($"成功,随机数为{random}");
});
retryForever.Execute(() => { DivideByZero(random); });
}
public static int DivideByZero(int random)
{
//int a = 0;
if (random != 25) random = 0;
return 100 / random;
}
}
}