一 模式介绍
重试模式,是应用在异常处理中,发生异常的时候,能够对业务程序进行重新调用,在实际中,可以使用Polly提供稳定,简单的用法,自己实现主要是对模式的一种了解。
二 模式实现
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
|
public class RetryPattern { /** * 重试模式可以用Polly替代 * 自己实现一种模式 */ #region 构造函数 public RetryPattern() { } #endregion 构造函数 #region 变量 private uint MaxTryCount; // 最大重试次数 private uint CurrentTryCount; // 当前重试的次数 private bool RunResult = true ; // 执行结果 #endregion 变量 #region 方法 #region 设置最大重试次数 public void SetMaxCount( uint tryCount) { // 校验 if (tryCount == 0) throw new ArgumentException( "重试次数不能为0" ); MaxTryCount = tryCount; } #endregion 设置最大重试次数 #region 是否需要重试 public bool IsRetry() { if (RunResult || CurrentTryCount == MaxTryCount) return false ; else { RunResult = true ; return true ; } } #endregion 是否需要重试 #region 获取当前重试次数 public uint GetCurrentTryCount() { return CurrentTryCount + 1; } #endregion 获取当前重试次数 #region 重试 public void RetryHandle() { RunResult = false ; CurrentTryCount++; } #endregion 重试 #endregion 方法 } |
ps:下面通过代码看下C# 异常重试策略
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
|
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Polly; using Polly.Bulkhead; using Polly.CircuitBreaker; using Polly.Fallback; using Polly.NoOp; using Polly.Registry; using Polly.Retry; using Polly.Timeout; using Polly.Utilities; using Polly.Wrap; using System.Net.Http; namespace CircuitBreak_Test { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click( object sender, EventArgs e) { try { var retryTwoTimesPolicy = Policy .Handle<DivideByZeroException>() .Retry(3, (ex, count) => { Console.WriteLine( "执行失败! 重试次数 {0}" , count); Console.WriteLine( "异常来自 {0}" , ex.GetType().Name); }); retryTwoTimesPolicy.Execute(() => { Compute(); }); } catch (DivideByZeroException e1) { Console.WriteLine($ "Excuted Failed,Message: ({e1.Message})" ); } Policy policy = Policy.Handle<TimeoutException>() .WaitAndRetryAsync(5, retryAttempt => TimeSpan.FromSeconds(5), (exception, retryCount) => { //logger.Error(exception); string xx = "" ; }); var result = policy.ExecuteAsync(() => Test()); Policy _circuitBreakerPolicy = Policy .Handle<HttpRequestException>() .Or<TimeoutRejectedException>() .Or<TimeoutException>() .CircuitBreakerAsync( exceptionsAllowedBeforeBreaking: 5, durationOfBreak: new TimeSpan(), onBreak: (ex, breakDelay) => { }, onReset: () => { }, onHalfOpen: () => { } ); var fallBackPolicy = Policy< string > .Handle<Exception>() .Fallback( "执行失败,返回Fallback" ); var fallBack = fallBackPolicy.Execute(() => { throw new Exception(); }); Console.WriteLine(fallBack); } static int Compute() { var a = 0; return 1 / a; } private static async Task Test() { using (HttpClient httpClient = new HttpClient()) { var response = httpClient.GetAsync( "http://news1.cnblogs.com/Category/GetCategoryList?bigCateId=11&loadType=0" ).Result; await response.Content.ReadAsStringAsync(); } } } } |
到此这篇关于C#异常执行重试的一种实现方法的文章就介绍到这了,更多相关C#异常重试内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://www.cnblogs.com/slowzero/p/15193522.html