重试C#HttpClient不成功的请求和超时

时间:2014-09-21 22:33:55

标签: c# enterprise-library dotnet-httpclient

我正在尝试在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之类的所有案例。

还有其他想法吗?

1 个答案:

答案 0 :(得分:6)

您可能只想要子类化(或换行)HttpClient;在HttpClient级别而不是在处理程序级别重试请求对我来说似乎更干净。如果这不合适,那么你需要将&#34;超时&#34;分开。值。

由于您的处理程序实际上在一个中执行了多个结果,因此HttpClient.Timeout适用于整个过程,包括重试。您可以向处理程序添加另一个超时值,即每个请求超时,并将其与链接的取消令牌源一起使用:

public class RetryDelegatingHandler : DelegatingHandler {
  public TimmeSpan PerRequestTimeout { get; set; }
  ...
  protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
  {
    var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
    cts.CancelAfter(PerRequestTimeout);
    var token = cts.Token;
    ...
        responseMessage = await base.SendAsync(request, token);
    ...
  }
}