1. 背景:系统偶然出现SSL错误,导致程序出现异常,造成数据不完整。
2. 目的:添加重试机制,当出现SSL错误且程序抛异常时,重新执行“接口”,以此解决SSL困扰。
/// <summary>
/// 代码执行失败重试帮助类
/// @Author wangrc
/// @Copy-Right 2022-03-21
/// @Version latest
/// @Getting-Start 参考FailureRetryHelper.TestFailureRetryHelper()
/// </summary>
public class FailureRetryHelper
{
/// <summary>
/// 使用示例
/// </summary>
public static async void TestFailureRetryHelper()
{
//创建一个空日志记录
ILogger logger = null;
//示例1
FailureRetryHelper.RetryRemote<string>(() =>
{
return "Test";
}, 10, 200, logger);
//注:示例1等价于 private string Test(){return "Test";}
FailureRetryHelper.RetryRemote(Test, 10, 200);
//FailureRetryHelper.RetryRemote<string>(Test, 10, 200, logger);
//示例2
FailureRetryHelper.RetryRemote(() =>
{
int i = 0;
}, 10, 200, logger);
//示例3
await FailureRetryHelper.RetryRemoteAsync(async () =>
{
return await Task.Run(()
=> { return Task.FromResult("Test"); });
}, 10, 200, logger);
//示例4
await FailureRetryHelper.RetryRemoteAsync(async () =>
{
await Task.Run(() => {
Task.FromResult("Test"); });
}, 10, 200, logger);
}
//private static string Test() { return "Test"; }
/// <summary>
/// -失败重试
/// -有返回值/// -同步
/// </summary>
/// <param name="func">执行的方法</param>
/// <param name="time">重试次数</param>
/// <param name="timeWait">等待时间</param>
/// <param name="logger">日志记录-可选</param>
/// <returns></returns>
public static T RetryRemote<T>(Func<T> func, int time, int timeWait, ILogger
logger = null)
{
for (var i = 0; i < time; i++)
{
try
{
var result = func();
return result;
}
catch (Exception ex)
{
Thread.Sleep(timeWait);
if (logger != null)
logger.LogInformation($"请求失败,开始重试 -第 {i} 次尝试,异常信
息:{ex}");
}
}
throw new Exception($"Http请求失败,重试次数{time}");
}
使用方法:在调用api接口(POST/GET/PUT/DELETE)的方法里调用重试帮助方法。
以下我单独对Delete方法举例: