我有以下Retry和Circuit Breaker策略:
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);如果使用自定义异常,则在记录以下内容后,重试将失败:
如果我使用标准的Exception类型,它可以正常工作。再试火,即使当断路器是打开:
var waitAndRetryPolicy = Policy
.Handle<Exception>()
.WaitAndRetryForeverAsync(
attempt => TimeSpan.FromMilliseconds(500),
(exception, calculatedWaitDuration) =>
{
_logger.LogInfo(exception.GetType().FullName);
_logger.LogInfo(".Log,then retry: " + exception.Message);
});发布于 2020-07-03 08:31:07
当断路器打开时,所有后续请求都会立即被BrokenCircuitException拒绝。这意味着,如果重试在这段时间内,当断路器是打开的时候,它将不会处理它,如果你只是寻找自定义的例外。这就是为什么你的弹性策略结束在那里,并抛出异常。
如果您想对这两种情况进行重试(当“电路断路器”打开时,以及在引发自定义异常时),则必须使用Or<>构建器函数。
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次尝试。
https://stackoverflow.com/questions/62698046
复制相似问题