orangesoft / backoff
退避算法实现。
5.0.0
2024-07-01 08:27 UTC
Requires
- php: ^8.1
- beberlei/assert: ^3.3
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.10
- php-parallel-lint/php-console-highlighter: ^1.0
- php-parallel-lint/php-parallel-lint: ^1.3
- phpbench/phpbench: ^1.2
- phpunit/phpunit: ^9.5
- psalm/plugin-phpunit: ^0.17.0
- vimeo/psalm: ^4.26
README
退避算法实现。
安装
您可以通过 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\CallbackBackOff
- Oranesoft\BackOff\ConstantBackOff
- Oranesoft\BackOff\DecorrelatedJitterBackOff
- Oranesoft\BackOff\ExponentialBackOff
- Oranesoft\BackOff\FibonacciBackOff
- Oranesoft\BackOff\LinearBackOff
启用抖动
将 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] |
+---------+---------------------------+--------------------+
以下抖动可用
- Oranesoft\BackOff\Jitter\EqualJitter
- Oranesoft\BackOff\Jitter\FullJitter
- Oranesoft\BackOff\Jitter\ScatteredJitter
在 AWS 架构博客 上阅读更多关于退避和抖动的内容。