如何在RetryPolicy <httpresponsemessage>上使用策略包装?

时间:2018-12-27 08:35:22

标签: 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);

这给出了错误:cannot convert from 'Polly.Retry.RetryPolicy<System.Net.Http.HttpResponseMessage>' to 'Polly.IAsyncPolicy'

1 个答案:

答案 0 :(得分:1)

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

这将使返回的策略的类型满足通用接口IAsyncPolicy<HttpResponseMessage>而非非通用IAsyncPolicy的类型。

要使用PolicyWrap static syntax创建泛型PolicyWrap<TResult>,必须明确指定泛型类型参数:

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

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

retryPolicy.WrapAsync(circuitBreaker).WrapAsync(sharedBulkhead)

Polly文档在the readmewiki中涵盖了非通用策略和通用策略之间的差异。