gpt4 book ai didi

c# - 尝试包装 2 个 Polly 策略时出现转换错误

转载 作者:行者123 更新时间:2023-12-03 08:51:11 24 4
gpt4 key购买 nike

我试图包装两个 Polly 策略并希望返回 IAsyncPolicy,但它给出错误,

convert from Polly.Retry.RetryPolicy < System.Net.Http.HttpResponseMessage> to 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 中非通用和通用策略之间的差异。 .

关于c# - 尝试包装 2 个 Polly 策略时出现转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58852615/

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