【发布时间】:2021-02-15 18:54:14
【问题描述】:
我正在使用 polly DecorrelatedJitterBackoff 策略重试 http 请求。我的用例是,当 timeSpan 达到 300 秒时,它应该每 300 秒重试 int.maximum 次。
我正在尝试使用以下代码来实现这一点。我使用了 int.MaxValue,它给出了超出范围的异常,所以我使用的是 2100000000。代码有效,但执行时间过长。请提出一种有效的方法来实现这一点?
private static readonly List<int> ExceptionCodes = new List<int> { 408, 429, 500, 503, 504, 520 };
var delay = Backoff.DecorrelatedJitterBackoffV2(medianFirstRetryDelay: TimeSpan.FromMilliseconds(2500), 10);
var decorrelatedJitterDelay = this.GetTimeSpanList(delay.ToArray());
this.RetryPolicy = Policy.HandleResult<HttpResponseMessage>(r => ExceptionCodes.Contains((int)r.StatusCode))
.WaitAndRetryAsync(decorrelatedJitterDelay);
var policyResult = this.RetryPolicy.ExecuteAndCaptureAsync(() => this.RequestServer(equipmentId));
private IEnumerable<TimeSpan> GetTimeSpanList(TimeSpan[] delay)
{
var index = 0;
var timeSpanList = new List<TimeSpan>();
foreach (var time in delay)
{
if (time > TimeSpan.FromSeconds(300))
{
var timeDelay = TimeSpan.FromSeconds(300);
delay[index] = timeDelay;
timeSpanList.Add(delay[index]);
}
index++;
}
// 2100000000 is the maximum capacity of List<>.
for (int i = index; i < 2100000000 - index; i++)
{
timeSpanList.Add(TimeSpan.FromSeconds(300));
}
return timeSpanList;
}
提前致谢
【问题讨论】: