【问题标题】:Transient Polly retry not working for HttpResponseMessageTransient Polly 重试不适用于 HttpResponseMessage
【发布时间】:2019-02-22 01:29:00
【问题描述】:

嗨,我想暗示波利重试瞬态错误处理我很有趣,但重试对我不起作用,请告诉我我错在哪里。

 var retryPolicy = Policy
        .HandleResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.Unauthorized

                                           || r.StatusCode == HttpStatusCode.GatewayTimeout
                                           || r.StatusCode == HttpStatusCode.RequestTimeout
                                           || r.StatusCode == HttpStatusCode.ServiceUnavailable)
    .WaitAndRetry(3, i => TimeSpan.FromSeconds(2), (result, timeSpan, retryCount, context) =>
    {
        Console.WriteLine($"Request failed with {result.Result.StatusCode}. Waiting {timeSpan} before next retry. Retry attempt {retryCount}");
    });

    retryPolicy.Execute(() =>
   {
        response = FailedOperation();
       return response;

   });

     private static HttpResponseMessage FailedOperation()
    {
 Console.WriteLine("Exception !!!!!");

    throw new HttpResponseException(HttpStatusCode.GatewayTimeout);
    }

【问题讨论】:

    标签: c# asp.net asp.net-mvc http-response-codes polly


    【解决方案1】:

    自定义的FailedOperation() 方法不涉及任何相关的.NET 框架/ASP.NET 基础设施,因此您正在测试的代码执行不会神奇地转换:

    throw new HttpResponseException(HttpStatusCode.GatewayTimeout); 
    

    HttpResponseMessageStatusCode。 Polly 也不这样做(Polly 对任何委托执行都是通用的,与 http 执行无关)。您发布的FailedOperation() 方法只是抛出一个HttpResponseException,纯粹而简单。

    该策略未声明为处理HttpResponseException,因此它不会处理它。像这样添加一个子句.Or&lt;HttpResponseException&gt;()

    var retryPolicy = Policy
        .HandleResult<HttpResponseMessage>(r => /* etc */)
        .Or<HttpResponseException>();
    

    并且策略应该处理它并使测试代码按照我认为问题所期望的方式运行。或者,您可以修改 FailedOperation() 以返回带有 HttpStatusCode 策略句柄的 HttpResponseMessage,同样,测试代码应该按预期运行。

    最后,如果策略是通过HttpClient 保护异步调用,您可能希望使用async variants of policies 作为Polly readme examples around Http calls suggest

    【讨论】:

    • 我可以在句柄请求中给出多个条件吗,因为在我的情况下,我在句柄请求中指定了 3-4 个条件,但在这种情况下,polly 重试不起作用,这就是我不想使用的原因。或();因为在那种情况下,我指定的条件适用于每个 HttpResponseException
    • 您可以给出多个条件并且它们起作用(我的回答描述了为什么您发布的案例没有按预期运行;这与多个条件无关)。您还可以使用.Or&lt;HttpResponseException&gt;() 子句中的条件进行更精细的过滤,例如shown here in the documentation。 Polly 有单元测试证明这些方面是有效的。如果其他事情没有按预期工作,请提供新的example failing code
    猜你喜欢
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    • 2022-07-14
    • 2018-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多