首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WaitRetryForever不适用于Polly.Net Resiliency中的自定义异常

WaitRetryForever不适用于Polly.Net Resiliency中的自定义异常
EN

Stack Overflow用户
提问于 2020-07-02 13:57:51
回答 1查看 640关注 0票数 0

我有以下RetryCircuit Breaker策略:

代码语言:javascript
复制
var waitAndRetryPolicy = Policy
    .Handle<Exception>(e => e is MycustomException)
    .WaitAndRetryForeverAsync(
        attempt => TimeSpan.FromMilliseconds(500),
        (exception, calculatedWaitDuration) =>
        {
            _logger.LogInfo(exception.GetType().FullName);
            _logger.LogInfo(".Log,then retry: " + exception.Message);
        });

var circuitBreakerPolicy = Policy
    .Handle<Exception>()
    .CircuitBreakerAsync(
        4,
        TimeSpan.FromSeconds(10),
        (ex, breakDelay) =>
        {
            _logger.LogError(".Breaker logging: Breaking the circuit for " + breakDelay.TotalMilliseconds + "ms!");
        },
        () => { _logger.LogError(".Breaker logging: Call ok! Closed the circuit again!"); },
        () => { _logger.LogError(".Breaker logging: Half-open: Next call is a trial!"); }
    );

return waitAndRetryPolicy.WrapAsync(circuitBreakerPolicy);

如果使用自定义异常,则在记录以下内容后,重试将失败:

  • 断路器测井:中断10000 for的电路!

如果我使用标准的Exception类型,它可以正常工作。再试火,即使当断路器是打开:

代码语言:javascript
复制
 var waitAndRetryPolicy = Policy
.Handle<Exception>()
.WaitAndRetryForeverAsync(
    attempt => TimeSpan.FromMilliseconds(500),
    (exception, calculatedWaitDuration) =>
    {
        _logger.LogInfo(exception.GetType().FullName);
        _logger.LogInfo(".Log,then retry: " + exception.Message);
    });
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-03 08:31:07

当断路器打开时,所有后续请求都会立即被BrokenCircuitException拒绝。这意味着,如果重试在这段时间内,当断路器是打开的时候,它将不会处理它,如果你只是寻找自定义的例外。这就是为什么你的弹性策略结束在那里,并抛出异常。

如果您想对这两种情况进行重试(当“电路断路器”打开时,以及在引发自定义异常时),则必须使用Or<>构建器函数。

代码语言:javascript
复制
var waitAndRetryPolicy = Policy
    .Handle<Exception>(e => e is MycustomException)
    .Or<BrokenCircuitException>
    .WaitAndRetryForeverAsync(
        attempt => TimeSpan.FromMilliseconds(500),
        (exception, calculatedWaitDuration) =>
        {
            _logger.LogInfo(exception.GetType().FullName);
            _logger.LogInfo(".Log,then retry: " + exception.Message);
        });

请记住时间在这里是很重要的。你的断路器等待10秒后,它就会转变成半开放状态。在此期间,重试将尝试执行几次尝试,但它们将立即失败。每次尝试失败后,它都会睡上500毫秒。这意味着在10秒内(当断路器打开时),重试以瞬间失败执行~20次尝试。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62698046

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档