我正在尝试包装两个 Polly 策略并想返回IAsyncPolicy
,但它给出了错误,
从 Polly.Retry.RetryPolicy
转换为 Polly.IAsyncPolicy
public static IAsyncPolicy CreateDefaultRetryPolicy()
{
var timeoutPolicy = Policy.TimeoutAsync(TimeSpan.FromSeconds(180));
var waitAndRetryPolicy = Polly.Policy
.Handle<HttpRequestException>()
.OrResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.InternalServerError)
.WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(3, retryAttempt)),
(result, timeSpan, context) =>
{
});
return Policy.WrapAsync(timeoutPolicy, waitAndRetryPolicy);
}
如何包装并返回?
按如下方式调整代码:
public static IAsyncPolicy<HttpResponseMessage> CreateDefaultRetryPolicy()
{
var timeoutPolicy = Policy.TimeoutAsync(TimeSpan.FromSeconds(180));
var waitAndRetryPolicy = Polly.Policy
.Handle<HttpRequestException>()
.OrResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.InternalServerError)
.WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(3, retryAttempt)),
(result, timeSpan, context) =>
{
});
return timeoutPolicy.WrapAsync(waitAndRetryPolicy);
}
解释
- 超时策略是非通用的,
IAsyncPolicy
。 - 等待重试策略是通用的,
IAsyncPolicy<HttpResponseMessage>
,因为它处理HttpResponseMessage
结果。
要在 PolicyWrap 中组合这些内容,请使用.Wrap(...)
实例方法语法:
return timeoutPolicy.WrapAsync(waitAndRetryPolicy);
由于生成的PolicyWrap处理HttpResponseMessage
,它也属于IAsyncPolicy<HttpResponseMessage>
类型,因此方法返回类型更改为该类型。
Polly 文档涵盖了 wiki 中非通用策略和通用策略之间的差异。