使用 Polly.Net 的嵌套重试和断路器策略的意外行为

Die*_*mos 2 c# circuit-breaker .net-core polly asp.net-core

我编写了基于重试的弹性策略和熔断策略。现在可以工作,但其行为存在问题。

我注意到,当断路器打开half-open并且onBreak()事件再次执行以关闭电路时,会为重试策略触发一次额外的重试(这是状态的另一项the health verificationhalf-open

让我一步步解释:

我定义了两个用于重试和断路器的强类型策略:

static Policy<HttpResponseMessage> customRetryPolicy;
static Policy<HttpResponseMessage> customCircuitBreakerPolicy;

static HttpStatusCode[] httpStatusesToProcess = new HttpStatusCode[]
{
   HttpStatusCode.ServiceUnavailable,  //503
   HttpStatusCode.InternalServerError, //500
};
Run Code Online (Sandbox Code Playgroud)

重试策略的工作方式如下:每个请求两次 (2) 重试,每次重试之间等待五 (5) 秒。如果内部断路器打开,不得重试。仅重试 500 和 503 Http 状态。

customRetryPolicy = Policy<HttpResponseMessage>   

//Not execute a retry if the circuit is open
.Handle<BrokenCircuitException>( x => 
{
    return !(x is BrokenCircuitException);
})

//Stop if some inner exception match with BrokenCircuitException
.OrInner<AggregateException>(x =>
{
    return !(x.InnerException is BrokenCircuitException);
})

//Retry if status are:
.OrResult(x => { return httpStatusesToProcess.Contains(x.StatusCode); })

// Retry request two times, wait 5 seconds between each retry
.WaitAndRetry( 2, retryAttempt => TimeSpan.FromSeconds(5),
    (exception, timeSpan, retryCount, context) =>
    {
        System.Console.WriteLine("Retrying... " + retryCount);
    }
);
Run Code Online (Sandbox Code Playgroud)

断路器策略的工作方式如下:允许最多连续三 (3) 次故障,然后断开电路三十 (30) 秒。仅适用于 HTTP-500 开路。

customCircuitBreakerPolicy = Policy<HttpResponseMessage>

// handling result or exception to execute onBreak delegate
.Handle<AggregateException>(x => 
    { return x.InnerException is HttpRequestException; })

// just break when server error will be InternalServerError
.OrResult(x => { return (int) x.StatusCode == 500; })

// Broken when fail 3 times in a row,
// and hold circuit open for 30 seconds
.CircuitBreaker(3, TimeSpan.FromSeconds(30),
    onBreak: (lastResponse, breakDelay) =>{
        System.Console.WriteLine("\n Circuit broken!");
    },
    onReset: () => {
        System.Console.WriteLine("\n Circuit Reset!");
    },
    onHalfOpen: () => {
        System.Console.WriteLine("\n Circuit is Half-Open");
    }); 
Run Code Online (Sandbox Code Playgroud)

最后,这两个策略是这样嵌套的:

try
{
    customRetryPolicy.Execute(() =>
    customCircuitBreakerPolicy.Execute(() => {
       
       //for testing purposes "api/values", is returning 500 all time
        HttpResponseMessage msResponse
            = GetHttpResponseAsync("api/values").Result;
        
        // This just print messages on console, no pay attention
        PrintHttpResponseAsync(msResponse); 
        
        return msResponse;

   }));
}
catch (BrokenCircuitException e)
{
    System.Console.WriteLine("CB Error: " + e.Message);
}
Run Code Online (Sandbox Code Playgroud)

我所期望的结果是什么?

  1. 第一个服务器响应是 HTTP-500(如预期)
  2. 重试#1,失败(如预期)
  3. 重试#2,失败(如预期)
  4. 由于出现三个故障,断路器现已打开(如预期)
  5. 伟大的!这是工作,完美!
  6. 断路器在接下来的三十 (30) 秒内打开(如预期)
  7. 三十秒后,断路器半开(如预期)
  8. 一次尝试检查端点运行状况(如预期)
  9. 服务器响应是 HTTP-500(如预期)
  10. 断路器在接下来的三十 (30) 秒内打开(如预期)
  11. 问题在这里:当断路器已经打开时,会启动额外的重试!

看图片:

在此输入图像描述

在此输入图像描述

在此输入图像描述

我正在尝试理解这种行为。为什么当断路器第二次、第三次……N次断开时还要执行一次额外的重试?

我已经检查了重试的机器状态模型和断路器策略,但我不明白为什么要执行此额外的重试。

断路器流程: https://github.com/App-vNext/Polly/wiki/Circuit-Breaker#putting-it-all-together-

重试策略流程: https://github.com/App-vNext/Polly/wiki/Retry#how-polly-retry-works

这确实很重要,因为正在等待重试的时间(本例为 5 秒),最终,这对于高并发来说是浪费时间。

任何帮助/指导,将不胜感激。非常感谢。

Pet*_*ala 7

使用Polly.Context,您可以在两个策略之间交换信息(在您的情况下:重试和断路器)。上下文基本上是一个Dictionary<string, object>.

因此,技巧是在 上设置一个键,onBreak然后在sleepDurationProdiver.

让我们从内部断路器策略开始:

static IAsyncPolicy<HttpResponseMessage> GetCircuitBreakerPolicy()
{
    return Policy<HttpResponseMessage>
        .HandleResult(res => res.StatusCode == HttpStatusCode.InternalServerError)
        .CircuitBreakerAsync(3, TimeSpan.FromSeconds(2),
           onBreak: (dr, ts, ctx) => { ctx[SleepDurationKey] = ts; },
           onReset: (ctx) => { ctx[SleepDurationKey] = null; });
}
Run Code Online (Sandbox Code Playgroud)
  • 连续 3 次请求失败后它会中断
  • 它会保持该Open状态 2 秒,然后转换为HalfOpen
  • 它在上下文中设置一个durationOfBreak键值
  • 当 CB 返回“正常”Closed状态 ( onReset) 时,它会删除该值

现在,让我们继续重试策略:

static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy()
{
    return Policy<HttpResponseMessage>
    .HandleResult(res => res.StatusCode == HttpStatusCode.InternalServerError)
    .Or<BrokenCircuitException>()
    .WaitAndRetryAsync(4,
        sleepDurationProvider: (c, ctx) =>
        {
            if (ctx.ContainsKey(SleepDurationKey))
                return (TimeSpan)ctx[SleepDurationKey];
            return TimeSpan.FromMilliseconds(200);
        },
        onRetry: (dr, ts, ctx) =>
        {
            Console.WriteLine($"Context: {(ctx.ContainsKey(SleepDurationKey) ? "Open" : "Closed")}");
            Console.WriteLine($"Waits: {ts.TotalMilliseconds}");
        });
}
Run Code Online (Sandbox Code Playgroud)
  • 当 StatusCode 为 500 时触发
    • 或者当有一个BrokenCircuitException
  • 它最多触发 4 次(因此总共 5 次尝试)
  • 它根据上下文设置睡眠持续时间
    • 如果上下文中不存在密钥(CB 处于状态Open),则它将在 200 毫秒内返回
    • 如果键存在于上下文中(CB 未处于Open状态),则它将返回上下文中的值
      • 注意:您可以在此值上添加几百毫秒以避免竞争条件
  • onRetry它仅出于调试目的将一些值打印到内部控制台

最后让我们连接策略并测试它

const string SleepDurationKey = "Broken"; 
static HttpClient client = new HttpClient();
static async Task Main()
{
    var strategy = Policy.WrapAsync(GetRetryPolicy(), GetCircuitBreakerPolicy());
    await strategy.ExecuteAsync(async () => await Get());
}

static Task<HttpResponseMessage> Get()
{
    return client.GetAsync("https://httpstat.us/500");
}
Run Code Online (Sandbox Code Playgroud)
  • 它使用http://httpstat.us网站来模拟过载的下游
  • 它组合/链接了两个策略(CB 内部、重试外部)
  • Get以异步方式调用该方法

什么时候handledEventsAllowedBeforeBreaking是2

输出

Context: Closed
Waits: 200
Context: Open
Waits: 2000
Context: Open
Waits: 2000
Context: Open
Waits: 2000
Run Code Online (Sandbox Code Playgroud)

什么时候handledEventsAllowedBeforeBreaking是 3

输出

Context: Closed
Waits: 200
Context: Closed
Waits: 200
Context: Open
Waits: 2000
Context: Open
Waits: 2000
Run Code Online (Sandbox Code Playgroud)

handledEventsAllowedBeforeBreaking4是什么时候

输出

Context: Closed
Waits: 200
Context: Closed
Waits: 200
Context: Closed
Waits: 200
Context: Open
Waits: 2000
Run Code Online (Sandbox Code Playgroud)