使用Polly时收到错误'请求消息已被发送'

问题描述 投票:0回答:1

我目前正在使用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);
}

我有以下请求发件人:

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;
    }
}

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

System.InvalidOperationException:'请求消息已发送。无法多次发送相同的请求消息。

我知道这种情况正在发生,因为我再次发送相同的HttpRequest,但Polly Library不应该处理这样的问题吗?

c# httprequest httpresponse polly
1个回答
1
投票

那个例外:

System.InvalidOperationException:'请求消息已发送。无法多次发送相同的请求消息。

如果你thrown by the internals of HttpClient,是call directly into any .SendAsync(...) overload with an HttpRequestMessage which has already been sent

如果您使用的是.NET Core,建议的解决方案是使用Polly with HttpClientFactory:这可以通过DelegatingHandler中的HttpClient执行策略(例如重试)来解决上述异常。它还解决了socket-exhaustion problem可能由频繁创建/处置HttpClient引起的问题,该问题中的代码可能容易受到攻击。

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.