使用Polly重试

发布于 2025-01-24 17:31:48 字数 416 浏览 1 评论 0原文

这两个重试政策是否表示相同?

Policy
    .Handle<SomeExceptionType>()
    .WaitAndRetry(
        new[]
        {
            TimeSpan.FromMinutes(1),
            TimeSpan.FromMinutes(1),
            TimeSpan.FromMinutes(1)
        });
Policy
    .Handle<SomeExceptionType>()
    .WaitAndRetry(
        3,
        retryAttempt => TimeSpan.FromMinutes(1)
    );

Do these 2 retry policies indicate the same?

Policy
    .Handle<SomeExceptionType>()
    .WaitAndRetry(
        new[]
        {
            TimeSpan.FromMinutes(1),
            TimeSpan.FromMinutes(1),
            TimeSpan.FromMinutes(1)
        });
Policy
    .Handle<SomeExceptionType>()
    .WaitAndRetry(
        3,
        retryAttempt => TimeSpan.FromMinutes(1)
    );

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

悲凉≈ 2025-01-31 17:31:48

是的,他们也这样做。

这两个代码都定义了一个策略,该策略最多将执行相同的操作:初始尝试 +另外三次尝试。

两个过载之间的主要区别是:

  • 前者定义 static 方式的惩罚
    • 它可以预先定义不同尝试之间的延迟
  • 后者定义了 dynamic 方式的惩罚
    • 它可以根据即将发生的重试
    • 来计算延迟

您的第二个替代方案可以这样定义:

Policy
    .Handle<SomeExceptionType>()
    .WaitAndRetry(
        3,
        _ => TimeSpan.FromMinutes(1)
    );

使用丢弃操作员,您可以明确地说明您在sleepduration provider 计算新延迟。


为了清楚起见,我使用了惩罚 delay sleep 术语在这篇文章中可互换。


更新#1

这是两个示例,您可以利用动态惩罚计算。

指数向后 +抖动,

而不是在每次尝试之间等待相同的时间,建议使用越来越大的延迟为下游系统提供自我光的空间。因此,例如:2、4、8 ...

jitter 只是一个小的随机数,可以避免所有客户都试图同时发送重试尝试。因此,它会及时散布/分散客户的重试尝试。

const int maxDelayInMilliseconds = 32 * 1000;
var jitterer = new Random();
Policy
  .Handle<HttpRequestException>()
  .WaitAndRetryForever(
      retryAttempt =>
      {
          var calculatedDelayInMilliseconds = Math.Pow(2, retryAttempt) * 1000;
          var jitterInMilliseconds = jitterer.Next(0, 1000);

          var actualDelay = Math.Min(calculatedDelayInMilliseconds + jitterInMilliseconds, maxDelayInMilliseconds);
          return TimeSpan.FromMilliseconds(actualDelay);
      }
  );

断路器意识到重试

如果您使用断路器以避免在自我修复时避免下游系统泛滥,则可以使您的重试知道这一点。

默认情况下,所有政策都是独立的,它们彼此之间没有意识。如果您在打开CB时进行重试尝试,则您将收到BROKENCIRCUITEXCEPTION(因此,它会缩短执行)。但是您可以根据CB的状态动态计算延迟,以便您可以跳过这些不必要的重试。

断路器定义

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; });

重试定义

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);
        });

此高级用例详细描述在这里

Yes, they do the same.

Both code defines a policy which will execute the same operation at most 4 times: the initial attempt + three additional attempts.

The main difference between the two overloads is the following:

  • The former defines the penalties in a static way
    • it predefines the delays between the different attempts
  • The latter defines the penalties in a dynamic way
    • it can compute the delays based on which retry is about to happen

In your particular example your second alternative can be defined like this:

Policy
    .Handle<SomeExceptionType>()
    .WaitAndRetry(
        3,
        _ => TimeSpan.FromMinutes(1)
    );

With the discard operator you are explicitly stating that you are not using that parameter inside the sleepDurationProvider to calculate the new delay.


For the sake of clarity I've used the penalty, delay and sleep terms interchangeable in this post.


UPDATE #1

Here are two examples where you can take advantage of the dynamic penalty calculation.

Exponential backoff + jitter

Rather than waiting the same amount of time between each attempts it is advisable to use larger and larger delays to give space for the downstream system to selfheal. So, for example: 2, 4, 8 ...

The jitter is just a small random number to avoid that all clients are trying to send their retry attempts at the same time. So it scatters/disperse the clients' retry attempts in time.

const int maxDelayInMilliseconds = 32 * 1000;
var jitterer = new Random();
Policy
  .Handle<HttpRequestException>()
  .WaitAndRetryForever(
      retryAttempt =>
      {
          var calculatedDelayInMilliseconds = Math.Pow(2, retryAttempt) * 1000;
          var jitterInMilliseconds = jitterer.Next(0, 1000);

          var actualDelay = Math.Min(calculatedDelayInMilliseconds + jitterInMilliseconds, maxDelayInMilliseconds);
          return TimeSpan.FromMilliseconds(actualDelay);
      }
  );

Circuit Breaker aware Retry

If you are using a circuit breaker to avoid flooding downstream system while it's self-healing you can make your retry aware of this.

By default all policies are independent and they are unaware of each other. If you issue a retry attempt while the CB is open then you will receive a BrokenCircuitException (so it short-cuts the execution). But you can dynamically calculate the delay based on the CB's state so you can skip these unnecessary retries.

The Circuit Breaker definition

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; });

The retry definition

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);
        });

This advanced use case is described in detail here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文