如果出现异常波莉框架CircuitBreakerAsync不重试 [英] Polly framework CircuitBreakerAsync does not retry if exception occur

查看:1186
本文介绍了如果出现异常波莉框架CircuitBreakerAsync不重试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用波莉框架瞬态故障处理。对于同步操作波利断路器政策工作正常,但是当我创造了异步版本,它不重试执行。请提示:

I am using Polly framework for transient fault handling. For synchronous operations Polly circuit breaker policy works fine but when I created its async version it does not retries the execution. Kindly suggest :

异步方法

private async static Task HelloWorld()
    {
        if (DateTime.Now < programStartTime.AddSeconds(10))
        {
            Console.WriteLine("Task Failed.");
            throw new TimeoutException();
        }
        await Task.Delay(TimeSpan.FromSeconds(1));
        Console.WriteLine("Task Completed.");
    }

波利断路器异步政策:

private static void AsyncDemo3(Func<Task> action)
    {
        programStartTime = DateTime.Now;

        Policy policy = Policy
            .Handle<TimeoutException>()
            .CircuitBreakerAsync(3, TimeSpan.FromSeconds(2));
        try
        {
            var a = policy.ExecuteAndCaptureAsync(action, true).GetAwaiter().GetResult();
        }
        catch (AggregateException ex)
        {
            Console.WriteLine("Exception: " + ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception: " + ex.Message);
        }
    }

执行波利断路器政策:

AsyncDemo3(的HelloWorld);

AsyncDemo3(HelloWorld);

请帮助查找和解决问题。

Kindly help the find and resolve the problem.

推荐答案

我相信你误解了断路器的政策做了什么。

I believe you misunderstood what the circuit breaker policy does.

它的作用是,如果的的称呼它为给定的次数,它每次都失败,那么它将停止呼吁一定的时间给定的方法。但它本身不重试。

What it does is that if you call it the given number of times and it fails each time, then it will stop calling the given method for a certain amount of time. But it does not retry by itself.

所以,我们要做什么,我想你想做的事情,你需要重试的政策与断路器的政策结合起来。要做到这一点的方法之一是:

So to do what I think you want to do, you need to combine retry policy with circuit breaker policy. One way to do that would be:

Policy retryPolicy = Policy.Handle<TimeoutException>().RetryAsync(3);

Policy circuitBreakerPolicy = Policy
    .Handle<TimeoutException>()
    .CircuitBreakerAsync(3, TimeSpan.FromSeconds(2));

try
{
    retryPolicy.ExecuteAsync(() => circuitBreakerPolicy.ExecuteAsync(action, true))
        .GetAwaiter().GetResult();
}
…

这code的输出是:

Task Failed.
Task Failed.
Task Failed.
Exception: The circuit is now open and is not allowing calls.

这篇关于如果出现异常波莉框架CircuitBreakerAsync不重试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆