使用 Polly 时收到错误“请求消息已发送”

Rya*_*zon 3 c# httpresponse httprequest polly

我目前正在使用 Polly 来限制我发送的请求数量。这是我目前的政策:

private AsyncPolicyWrap<HttpResponseMessage> DefineAndRetrieveResiliencyStrategy()
{
    HttpStatusCode[] retryCodes = {
       HttpStatusCode.InternalServerError,
       HttpStatusCode.BadGateway,
       HttpStatusCode.GatewayTimeout
    };

    var waitAndRetryPolicy = Policy
        .HandleResult<HttpResponseMessage>(e => e.StatusCode == HttpStatusCode.ServiceUnavailable || e.StatusCode == (HttpStatusCode)429)
        .WaitAndRetryAsync(10,
            attempt => TimeSpan.FromSeconds(5), (exception, calculatedWaitDuration) =>
            {
                _log.Info($"Bitfinex API server is throttling our requests. Automatically delaying for {calculatedWaitDuration.TotalMilliseconds}ms");
            }
        );

    var circuitBreakerPolicyForRecoverable = Policy
        .Handle<HttpResponseException>()
        .OrResult<HttpResponseMessage>(r => retryCodes.Contains(r.StatusCode))
        .CircuitBreakerAsync(
            handledEventsAllowedBeforeBreaking: 3,
            durationOfBreak: TimeSpan.FromSeconds(3),
            onBreak: (outcome, breakDelay) =>
            {
                _log.Info($"Polly Circuit Breaker logging: Breaking the circuit for {breakDelay.TotalMilliseconds}ms due to: {outcome.Exception?.Message ?? outcome.Result.StatusCode.ToString()}");

            },
            onReset: () => _log.Info("Polly Circuit Breaker logging: Call ok... closed the circuit again"),
            onHalfOpen: () => _log.Info("Polly Circuit Breaker logging: Half-open: Next call is a trial")
        );

    return Policy.WrapAsync(waitAndRetryPolicy, circuitBreakerPolicyForRecoverable);
}
Run Code Online (Sandbox Code Playgroud)

我有以下请求发件人:

private async Task<string> SendRequest(GenericRequest request, string httpMethod, string publicKey, string privateKey)
{
    var resiliencyStrategy = DefineAndRetrieveResiliencyStrategy();

    using (var client = new HttpClient())
    using (var httpRequest = new HttpRequestMessage(new HttpMethod(httpMethod), request.request))
    {
        string json = JsonConvert.SerializeObject(request);
        string json64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(json));
        byte[] data = Encoding.UTF8.GetBytes(json64);

        client.BaseAddress = new Uri(Properties.Settings.Default.BitfinexUri);

        var hashMaker = new HMACSHA384(Encoding.UTF8.GetBytes(privateKey));
        byte[] hash = hashMaker.ComputeHash(data);
        string signature = GetHexString(hash);

        httpRequest.Headers.Add("X-BFX-APIKEY", publicKey);
        httpRequest.Headers.Add("X-BFX-PAYLOAD", json64);
        httpRequest.Headers.Add("X-BFX-SIGNATURE", signature);

        var message = await resiliencyStrategy.ExecuteAsync(() => client.SendAsync(httpRequest));
        var response = message.Content.ReadAsStringAsync().Result;

        return response;
    }
}
Run Code Online (Sandbox Code Playgroud)

一旦代码达到 waitAndRetryPolicy 并等待所需的时间,我就会收到以下错误:

System.InvalidOperationException: '请求消息已经发送。不能多次发送相同的请求消息。

我知道这是因为我再次发送相同的 HttpRequest 但 Polly 库不应该处理这样的问题吗?

mou*_*ler 11

那个例外:

System.InvalidOperationException: '请求消息已经发送。不能多次发送相同的请求消息。

被通过的内部抛出HttpClient,如果你直接打电话到任何.SendAsync(...)过载与HttpRequestMessage已经被发送。

如果使用的是.NET核心,推荐的解决方案是使用波利用HttpClientFactory:经由这解决了通过执行策略(例如重试)上述异常的DelegatingHandler内HttpClient。它还解决了可能由频繁 create/dispose of 引起的套接字耗尽问题,问题中HttpClient发布的代码可能容易受到攻击。

如果您使用 .NET 框架,推荐的解决方案是:

  • 复制 HttpClientFactory 在 DelegatingHandler 中放置策略的方式;或者
  • 重构您的代码以HttpRequestMessage在通过策略执行的代码中制造(或克隆现有实例)的新实例。

这个stackoverflow问题广泛讨论了上述解决方案的问题和许多变体。