如何使用dotnet core和Polly添加动态重试策略

时间:2018-10-01 20:48:10

标签: c# exception-handling .net-core polly retrypolicy

我有一个dotnet核心(2.1)控制台应用程序,并且我正在使用Polly使用重试策略包装我的代码段。使用下面显示的简单用例,效果很好:

private void ProcessRun() 
{
    var policy = Policy.Handle<SocketException>().WaitAndRetryAsync(
                 retryCount: 3
                 sleepDurationProvider: attempt => TimeSpan.FromSeconds(10),
                 onRetry: (exception, calculatedWaitDuration) => 
                 {
                    Console.WriteLine($"Retry policy executed for type SocketException");
                 });

    try
    {
        CancellationTokenSource _cts = new CancellationTokenSource()

        PollyRetryWaitPolicy.ExecuteAsync(async token => {
           MyOperation(token);
        }, _cts.Token)
        .ContinueWith(p => {
           if (p.IsFaulted || p.Status == TaskStatus.Canceled)
           {
                Console.WriteLine("faulted or was cancelled");
           }
        })
        .ConfigureAwait(false);
    }
    catch (Exception ex) {
     Console.WriteLine($"Exception has occurred: {ex.Message}");
    }
}

然后我使用以下代码对其进行测试:

private void MyOperation() 
{
    Thread.Sleep(2000);
    throw new SocketException();
}

执行代码时,将按预期捕获套接字异常。

我一直在寻找一种灵活的方式,用多个策略而不是一个策略来包装我的代码。我更改了代码,以动态地将多个包装的Polly Retry策略一起添加,以允许捕获多个错误类型并轻松更改我要查找的异常。我将代码更改为此:

internal PolicyWrap PollyRetryWaitPolicy;

public void AddRetryWaitPolicy<T>(int waitTimeInSeconds, int retryAttempts)
    where T: Exception
{

    // Setup the polly policy that will be added to the executing code.
    var policy = Policy.Handle<T>().WaitAndRetryAsync(
                retryCount: retryAttempts, 
                sleepDurationProvider: attempt => TimeSpan.FromSeconds(waitTimeInSeconds), 
                onRetry: (exception, calculatedWaitDuration) => 
                {
                    Console.WriteLine($"Retry policy executed for type {typeof(T).Name}");
                });

    if (host.PollyRetryWaitPolicy == null)
    {
        // NOTE: Only add this timeout policy as it seems to need at least one
        // policy before it can wrap! (suppose that makes sense).
        var timeoutPolicy = Policy
            .TimeoutAsync(TimeSpan.FromSeconds(waitTimeInSeconds), TimeoutStrategy.Pessimistic);
        PollyRetryWaitPolicy = policy.WrapAsync(timeoutPolicy);
    }
    else
    {
        PollyRetryWaitPolicy.WrapAsync(policy);
    }
}

private void ProcessRun() 
{
    AddRetryWaitPolicy<SocketException>(10, 5);
    AddRetryWaitPolicy<InvalidOperationException>(5, 2);

    try
    {
        Console.WriteLine($"Calling HostedProcess.Run() method. AwaitResult: {awaitResult}");

        CancellationTokenSource _cts = new CancellationTokenSource()

        PollyRetryWaitPolicy.ExecuteAsync(async token => {
           MyOperation(token);
        }, _cts.Token)
        .ContinueWith(p => {
           if (p.IsFaulted || p.Status == TaskStatus.Canceled)
           {
                Console.WriteLine("Process has faulted or was cancelled");
           }
        })
        .ConfigureAwait(false);
    }
    catch (Exception ex) {
     Console.WriteLine($"Exception has occurred: {ex.Message}");
    }
}

当我使用此代码进行测试时,以上代码按预期工作,并重试了5次。

private void MyOperation() 
{
    Thread.Sleep(2000);
    throw new SocketException();
}

但是,当我尝试以下操作时,它不会按预期重试2次(根本不会重试):

private void MyOperation() 
{
    Thread.Sleep(2000);
    throw new InvalidOperationException();
}

我在做什么错?以上所有内容的要点是根据我的需要动态地制定多个策略。除了WrapPolicy,还有其他更好的方法吗?

感谢提前提供指针!

1 个答案:

答案 0 :(得分:1)

这里:

if (host.PollyRetryWaitPolicy == null)
{
    // NOTE: Only add this timeout policy as it seems to need at least one
    // policy before it can wrap! (suppose that makes sense).
    var timeoutPolicy = Policy
        .TimeoutAsync(TimeSpan.FromSeconds(waitTimeInSeconds), TimeoutStrategy.Pessimistic);
    PollyRetryWaitPolicy = policy.WrapAsync(timeoutPolicy);
}
else
{
    PollyRetryWaitPolicy.WrapAsync(policy);
}

它似乎在if分支和else分支中采用了不一致的方法来对重试策略和超时策略进行排序。

  • if分支中,超时策略包装在重试策略中。因此,超时相当于每次尝试超时。
  • else分支中,所有现有的重试和超时策略都在新重试策略的外部中包装。因此,超时政策是 outside 新的重试政策。
    • 新的重试策略设置为在waitTimeInSeconds之后重试;但是超时策略也设置为在waitTimeInSeconds之后超时执行。因此,第一次重试(针对第二个或后续配置的重试策略)发生时,超时将中止整个执行。因此,如您所见,重试永远不会发生。

要解决此问题,您可以将else分支更改为:

PollyRetryWaitPolicy = policy.WrapAsync(PollyRetryWaitPolicy);

背景:请参见PolicyWrap wiki recommendations on ordering policies in a PolicyWrap。根据您将TimeoutPolicy放置在RetryPolicy的内部还是外部,TimeoutPolicy的作用是(内部)每次尝试超时,(外部)则是所有尝试的整体超时。 / p>