我同时使用改装和 Polly 来调用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 的正常重试政策是什么?您是否只是制动电路或在一般情况下会采取什么措施来恢复?
答案可能是“这取决于你的服务回报”,但我只想问。
答案 0 :(得分:1)
如果返回的ApiException
包含有意义的HttpStatusCode StatusCode
属性,您当然可以选择哪些StatusCodes值得重试; Polly readme建议:
int[] httpStatusCodesWorthRetrying = {408, 500, 502, 503, 504};
对于所调用的API的ApiException
,只知道这些特定于API的错误代表什么,可以指导是否重试它们。
如果您选择断断续续的某种类型的异常,应该通过将断路器包装到PolicyWrap
而不是在重试策略的onRetry
代表内来实现。 Polly讨论了为什么要断电?&#39; here,以及readme circuit-breaker section脚下许多其他断路器博客帖子的链接。