2

我同时使用RefitPolly来调用 restful API,我想知道 Refits ApiException 的重试(如果有的话)策略应该是什么?

public static PolicyWrap MyRetryPolicy()
{
        // Try few times with little more time between... maybe the 
        // connection issue gets resolved
        var wireServerNetworkIssue = Policy.Handle<WebException>() 
                                    .WaitAndRetryAsync(new[] {
                                    TimeSpan.FromSeconds(1),
                                    TimeSpan.FromSeconds(2),
                                    TimeSpan.FromSeconds(4)});
        var policyList = new List<Policy>();

        // But if there is something wrong with the api
        // I should do what (if general)?
        var api = Policy.Handle<ApiException>()
                  .RetryAsync(1, onRetry: async (exception, i) =>
                  {
                       await Task.Run(() =>
                       {
                           // What would be normal to do here?
                           // Try again or do some circuit braking?
                       });
                  });

        policyList.Add(wireServerNetworkIssue);
        policyList.Add(api);

        return Policy.Wrap(policyList.ToArray());
}

然后我像这样使用它

try
{
    myApi = RestService.For<MyApi>("api base url");
    var policyWrapper = Policies.Policies.MyRetryPolicyWrapper();
    var response  = await policy.ExecuteAsync(() => myApi.SendReceiptAsync(receipt));
}
catch (ApiException apiEx)
{
  //Do something if the retry policy did´t fix it.
}
catch (WebException webEx)
{
  //Do something if the retry policy did´t fix it.
}

问题

ApiExceptions的正常重试策略是什么?你会只是电路刹车还是在什么一般情况下你会做一些事情来恢复?

答案可能是“这取决于您的服务返回什么”,但我只需要问一下。

4

1 回答 1

2

如果ApiException返回的 s 包含有意义的HttpStatusCode StatusCode属性,您当然可以选择哪些 StatusCodes 值得重试;Polly 自述文件建议:

int[] httpStatusCodesWorthRetrying = {408, 500, 502, 503, 504}; 

对于ApiException调用的 API 特定的,只有知道那些 API 特定的错误代表什么,才能指导是否重试它们。

如果您选择对过多的某种异常进行熔断,则应通过将熔断器包装到您的 中来实现PolicyWrap,而不是在onRetry重试策略的委托中。Polly 讨论“为什么要断路?” 此处,以及在自述文件断路器部分底部的许多其他断路器博客文章的链接。

于 2017-03-25T11:48:43.897 回答