【发布时间】:2014-09-21 22:33:55
【问题描述】:
我正在尝试在 HttpClient DelegatingHandler 中构建重试,以便将 503 Server Unavailable 和超时等响应视为暂时失败并自动重试。
我从http://blog.devscrum.net/2014/05/building-a-transient-retry-handler-for-the-net-httpclient/ 的代码开始,它适用于403 Server Unavailable 的情况,但不会将超时视为暂时性故障。尽管如此,我还是喜欢使用 Microsoft 瞬态故障处理块来处理重试逻辑的总体思路。
这是我当前的代码。它使用自定义的Exception 子类:
public class HttpRequestExceptionWithStatus : HttpRequestException {
public HttpRequestExceptionWithStatus(string message) : base(message)
{
}
public HttpRequestExceptionWithStatus(string message, Exception inner) : base(message, inner)
{
}
public HttpStatusCode StatusCode { get; set; }
public int CurrentRetryCount { get; set; }
}
这是瞬态故障检测器类:
public class HttpTransientErrorDetectionStrategy : ITransientErrorDetectionStrategy {
public bool IsTransient(Exception ex)
{
var cex = ex as HttpRequestExceptionWithStatus;
var isTransient = cex != null && (cex.StatusCode == HttpStatusCode.ServiceUnavailable
|| cex.StatusCode == HttpStatusCode.BadGateway
|| cex.StatusCode == HttpStatusCode.GatewayTimeout);
return isTransient;
}
}
这个想法是超时应该变成ServiceUnavailable异常,就好像服务器已经返回了那个HTTP错误代码一样。这是DelegatingHandler 子类:
public class RetryDelegatingHandler : DelegatingHandler {
public const int RetryCount = 3;
public RetryPolicy RetryPolicy { get; set; }
public RetryDelegatingHandler(HttpMessageHandler innerHandler) : base(innerHandler)
{
RetryPolicy = new RetryPolicy(new HttpTransientErrorDetectionStrategy(), new ExponentialBackoff(retryCount: RetryCount,
minBackoff: TimeSpan.FromSeconds(1), maxBackoff: TimeSpan.FromSeconds(10), deltaBackoff: TimeSpan.FromSeconds(5)));
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var responseMessage = (HttpResponseMessage)null;
var currentRetryCount = 0;
EventHandler<RetryingEventArgs> handler = (sender, e) => currentRetryCount = e.CurrentRetryCount;
RetryPolicy.Retrying += handler;
try {
await RetryPolicy.ExecuteAsync(async () => {
try {
App.Log("Sending (" + currentRetryCount + ") " + request.RequestUri +
" content " + await request.Content.ReadAsStringAsync());
responseMessage = await base.SendAsync(request, cancellationToken);
} catch (Exception ex) {
var wex = ex as WebException;
if (cancellationToken.IsCancellationRequested || (wex != null && wex.Status == WebExceptionStatus.UnknownError)) {
App.Log("Timed out waiting for " + request.RequestUri + ", throwing exception.");
throw new HttpRequestExceptionWithStatus("Timed out or disconnected", ex) {
StatusCode = HttpStatusCode.ServiceUnavailable,
CurrentRetryCount = currentRetryCount,
};
}
App.Log("ERROR awaiting send of " + request.RequestUri + "\n- " + ex.Message + ex.StackTrace);
throw;
}
if ((int)responseMessage.StatusCode >= 500) {
throw new HttpRequestExceptionWithStatus("Server error " + responseMessage.StatusCode) {
StatusCode = responseMessage.StatusCode,
CurrentRetryCount = currentRetryCount,
};
}
return responseMessage;
}, cancellationToken);
return responseMessage;
} catch (HttpRequestExceptionWithStatus ex) {
App.Log("Caught HREWS outside Retry section: " + ex.Message + ex.StackTrace);
if (ex.CurrentRetryCount >= RetryCount) {
App.Log(ex.Message);
}
if (responseMessage != null) return responseMessage;
throw;
} catch (Exception ex) {
App.Log(ex.Message + ex.StackTrace);
if (responseMessage != null) return responseMessage;
throw;
} finally {
RetryPolicy.Retrying -= handler;
}
}
}
问题在于,一旦发生第一次超时,随后的重试会立即超时,因为所有内容都共享一个取消令牌。但是,如果我创建一个新的 CancellationTokenSource 并使用它的令牌,则不会发生超时,因为我无权访问原始 HttpClient 的取消令牌源。
我考虑过继承HttpClient 并覆盖SendAsync,但它的主要重载不是虚拟的。我可能只是创建一个不称为 SendAsync 的新函数,但它不是一个直接替换,我必须替换所有类似 GetAsync 的案例。
还有其他想法吗?
【问题讨论】:
-
请正确格式化您的代码。
-
这是为 Xamarin 编写的代码,它遵循 Mono Project 的大部分编码指南,位于 mono-project.com/community/contributing/coding-guidelines。
-
而且仍然非常不可读
标签: c# enterprise-library dotnet-httpclient