orangesoft/backoff

退避算法实现。

5.0.0 2024-07-01 08:27 UTC

This package is auto-updated.

Last update: 2024-09-09 08:10:01 UTC


README

Build Status Latest Stable Version Packagist PHP Version Support Total Downloads License

退避算法实现。

安装

您可以通过 Composer 安装最新版本

composer require orangesoft/backoff

此包需要 PHP 8.1 或更高版本。

快速使用

配置 Orangesoft\BackOff\Retry\Retry::class,任何退避类,以及 Orangesoft\BackOff\Retry\ExceptionClassifier\ExceptionClassifier::class,在抛出异常时重试业务逻辑

<?php

use Orangesoft\BackOff\ExponentialBackOff;
use Orangesoft\BackOff\Duration\Microseconds;
use Orangesoft\BackOff\Retry\ExceptionClassifier\ExceptionClassifier;
use Orangesoft\BackOff\Retry\Retry;

$retry = new Retry(
    maxAttempts: 3,
    backOff: new ExponentialBackOff(
        baseTime: new Microseconds(1_000),
        capTime: new Microseconds(512_000),
        factor: 2.0,
    ),
    exceptionClassifier: new ExceptionClassifier(
        classNames: [
            \RuntimeException::class,
        ],
    ),
);

使用 Orangesoft\BackOff\Retry\Retry::call(callable $callback): mixed 方法来包装业务逻辑并带有重试功能调用它

/** @var int $result */
$result = $retry->call(static function (): int {
    $random = mt_rand(0, 1);
    
    if (0 === $random % 2) {
        throw new \RuntimeException();
    }
    
    return $random;
});

以下退避策略可用

启用抖动

Oranesoft\BackOff\Jitter\JitterInterface::class 的实现传递给退避类,以启用抖动

<?php

use Orangesoft\BackOff\ExponentialBackOff;
use Orangesoft\BackOff\Duration\Microseconds;
use Orangesoft\BackOff\Jitter\EqualJitter;

$backOff = new ExponentialBackOff(
    baseTime: new Microseconds(1_000),
    capTime: new Microseconds(512_000),
    factor: 2.0,
    jitter: new EqualJitter(),
);

for ($i = 1; $i <= 10; $i++) {
    $backOff->backOff(
        attempt: $i,
    );
}

以下为指数退避的时间间隔(以微秒为单位),乘数为 2.0,抖动相等,基本时间为 1_000 μs,上限时间为 512_000 μs

+---------+---------------------------+--------------------+
| attempt | exponential back-off (μs) | equal jitter (μs)  |
+---------+---------------------------+--------------------+
|       1 |                     1_000 |         [0, 1_000] |
|       2 |                     2_000 |     [1_000, 2_000] |
|       3 |                     4_000 |     [2_000, 4_000] |
|       4 |                     8_000 |     [4_000, 8_000] |
|       5 |                    16_000 |    [8_000, 16_000] |
|       6 |                    32_000 |   [16_000, 32_000] |
|       7 |                    64_000 |   [32_000, 64_000] |
|       8 |                   128_000 |  [64_000, 128_000] |
|       9 |                   256_000 | [128_000, 256_000] |
|      10 |                   512_000 | [256_000, 512_000] |
+---------+---------------------------+--------------------+

以下抖动可用

AWS 架构博客 上阅读更多关于退避和抖动的内容。