标签进阶 / 大象重试
这是guava-retrying模块的移植版本,允许为任意函数调用创建可配置的重试策略,例如与具有不稳定在线时间的远程服务进行通信。
Requires
- php: ^7.4.0
- respect/validation: ^1.1
Requires (Dev)
- codeclimate/php-test-reporter: dev-master
- mockery/mockery: dev-master
- phpunit/phpunit: ^9.0
This package is auto-updated.
Last update: 2024-09-22 14:24:58 UTC
README
这是什么?
elephant-retrying模块提供了一个通用的方法,用于重试任意PHP代码,并具有特定的停止、重试和异常处理功能。
这是Ray Holder(rholder)在此处发布的优秀guava-retrying代码的分支。
移植适配
- 由于PHP不支持泛型,因此已删除泛型。
- 所有时间单位均已转换为浮点型秒。
- 已删除时间限制器,因为在PHP中实现此类功能将很困难。
Composer
composer require tagadvance/elephant-retrying
快速入门
以下是一些功能的最小示例
$retryer = RetryerBuilder::newBuilder() ->retryIfResult('is_null') ->retryIfExceptionOfType(\RuntimeException::class) ->withStopStrategy(StopStrategies . stopAfterAttempt(3)) ->build(); try { $retryer->call(fn() => true); // do something useful here } catch (RetryException $e) { print $e->getTraceAsString(); } catch (ExecutionException $e) { print $e->getTraceAsString(); }
这将会在Callable的结果为null、抛出IOException或从call()方法抛出任何其他RuntimeException时重试。它将在尝试重试3次后停止,并抛出一个包含最后一次失败尝试信息的RetryException。如果从call()方法中弹出任何其他Exception,它将包装并重新抛出ExecutionException。
指数退避
创建一个无限重试的Retryer,每次失败重试后等待增加的指数退避间隔,最多等待5分钟。5分钟后,每隔5分钟重试。
$maximumWaitTimeSeconds = 300; // 5 minutes $retryer = RetryerBuilder::newBuilder() ->retryIfExceptionOfType(\RuntimeException::class) ->withWaitStrategy(WaitStrategies::exponentialWait(1, $maximumWaitTimeSeconds)) ->withStopStrategy(StopStrategies::neverStop()) ->build();
您可以在指数退避和它在TCP/IP开发中的历史作用中了解更多信息拥塞避免和控制。
斐波那契退避
创建一个无限重试的Retryer,每次失败重试后等待增加的斐波那契退避间隔,最多等待2分钟。2分钟后,每隔2分钟重试。
$maximumWaitTimeSeconds = 120; // 2 minutes $retryer = RetryerBuilder::newBuilder() ->retryIfExceptionOfType(\RuntimeException::class) ->withWaitStrategy(WaitStrategies::fibonacciWait(1, $maximumWaitTimeSeconds)) ->withStopStrategy(StopStrategies::neverStop()) ->build();
与ExponentialWaitStrategy类似,FibonacciWaitStrategy在每次失败尝试后等待增加的时间量。
它使用的是(显然)斐波那契数列来计算等待时间,而不是指数函数。
根据问题,FibonacciWaitStrategy可能比ExponentialWaitStrategy表现更好,并且可以提高吞吐量——至少根据不同重传概率下不同退避算法的性能比较。
FibonacciWaitStrategy的实现使用斐波那契的迭代版本,因为(原始的)递归版本将在某个点上导致StackOverflowError(尽管在重试的有用参数下非常不可能)。
此实现的灵感来自有效的重试/退避机制。
来源
git clone git@github.com:tagadvance/elephant-retrying.git
清理、安装和测试
./make
许可
guava-retrying 模块是在 Apache License 2.0 许可下发布的。