c# - 如何在 RetryPolicy<HttpResponseMessage> 上使用策略包装?

标签 c# asp.net polly

我有以下使用 Polly.Extensions.Http 的重试策略:

var retryPolicy = Policy.Handle<BrokenCircuitException>().OrTransientHttpError().WaitAndRetryAsync
                (
                    retryCount: maxRetryCount,
                    sleepDurationProvider: attempt => TimeSpan.FromSeconds(Math.Pow(2, attempt)),
                    onRetryAsync: (exception, calculatedWaitDuration, retryCount, context) =>
                    {
                      //Code
                    }
                );

我想用断路器和舱头政策包装政策:

var circuitBreaker = Policy.Handle<HttpRequestException>().CircuitBreakerAsync(
            exceptionsAllowedBeforeBreaking: maxExceptionsBeforeBreaking,
            durationOfBreak: TimeSpan.FromSeconds(circuitBreakDurationSeconds),
            onBreak: (exception, timespan, context) =>
            {
              //Code
            },
            onReset: (context) =>
            {
                //Code
            }
        );

var sharedBulkhead = Policy.BulkheadAsync(
            maxParallelization: maxParallelizations,
            maxQueuingActions: maxQueuingActions,
            onBulkheadRejectedAsync: (context) =>
            {
                //Code
            }
        );

我使用以下代码将政策包装在一起:

Policy.WrapAsync(retryPolicy, circuitBreaker, sharedBulkhead);

这是一个错误:

can not convert from 'Polly.Retry.RetryPolicy<System.Net.Http.HttpResponseMessage>' to 'Polly.IAsyncPolicy'

最佳答案

当策略配置使用 .HandleTransientHttpError() or .OrTransientHttpError() 时,策略配置为处理 specific status code results执行返回 HttpResponseMessage .

这使得返回的策略类型满足通用接口(interface) IAsyncPolicy<HttpResponseMessage>而不是非通用的 IAsyncPolicy .

创建通用 PolicyWrap<TResult>使用 PolicyWrap static syntax您必须显式指定泛型类型参数:

Policy.WrapAsync<HttpResponseMessage>(retryPolicy, circuitBreaker, sharedBulkhead)

如果您使用 PolicyWrap instance syntax ,编译器通常可以推断语法。所以以下内容也应该足够了:

retryPolicy.WrapAsync(circuitBreaker).WrapAsync(sharedBulkhead)

Polly 文档涵盖了非通用策略和通用策略之间的差异,通常在 the readme 中和 wiki .

关于c# - 如何在 RetryPolicy<HttpResponseMessage> 上使用策略包装?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53942022/

相关文章:

c# - Resharper:无法在 VS2010 SP1 中解析符号 'Eval'

c# - 扩展 MVC-6 中的 ClaimsPrincipal 和 ClaimsIdentity 类

c# - 在 NSScrollView 中检测滚动事件

c# - 通过 Id 和名称获取下一个和上一个 sql 行,EF?

asp.net - <customErrors mode ="Off"/> 的用途是什么?

asp.net - 使用 AJAX 更改 ASP.NET 上的内容

c# - 将 httpclient 与 polly 策略一起使用时未捕获 TaskCanceledException

c# - .Net Core - 具有重试策略的 AWS DynamoDb

c# - 在 Polly 中结合 transient 故障捕获和重新授权

c# - ASP.NET Core 2 中的 ModelBinder 和日期