gpt4 book ai didi

c# - Refit ApiException 的最佳重试策略?

转载 作者:行者123 更新时间:2023-12-05 05:21:25 27 4
gpt4 key购买 nike

我同时使用 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 的正常重试策略?你会只是电路制动还是在什么一般情况下你会做些什么来恢复?

答案可能是“这取决于您的服务返回什么”,但我不得不问。

最佳答案

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

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

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

如果您选择对某种类型的太多异常进行熔断,那应该通过将熔断器包装到您的 PolicyWrap 中来实现。 ,而不是在重试策略的 onRetry 委托(delegate)中。 Polly 讨论“为什么要断路?” here ,并链接到 readme circuit-breaker section 脚下的许多其他断路器博客文章.

关于c# - Refit ApiException 的最佳重试策略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42932901/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com