fostam / retry
使用各种延迟策略重试任何可调用函数,直到成功或达到最大重试次数
Requires
- php: >=7.4
Requires (Dev)
- phpunit/phpunit: ^8.5
This package is auto-updated.
Last update: 2024-09-27 01:10:39 UTC
README
使用 Retry,您可以重复执行任何可调用函数,直到成功或达到最大尝试次数。提供了多种延迟策略来确定尝试之间的睡眠时间。
功能
- 简单使用
- 不同的延迟策略
- 与任何PHP可调用函数一起工作
- 无依赖
安装
安装 Retry 的最简单方法是使用 composer
$> composer require fostam/retry
用法
try { // sleep 1 second between attempts $funcResult = Retry::onFailure('myfunc', 3, new ConstantDelayPolicy(1000)); } catch (RetryLimitException $e) { // failed after maximum number of attempts } // success before maximum number of attempts have been exceeded
有效负载调用
有效负载调用可以是函数、类/对象方法或闭包,如PHP 文档中所述。
失败条件
如果有效负载调用抛出异常或返回 false
,则认为有效负载调用失败。如果 false
是您可调用函数的合法结果,请使用 onException()
而不是 onFailure()
,在这种情况下,将忽略可调用函数的返回值。
原始异常被链接到 RetryLimitException
,并通过 $e->getPrevious()
获取。
您还可以使用 onCondition()
方法并传递一个验证可调用函数,该函数接受有效负载可调用函数的结果作为参数,并返回 true
或 false
来指示原始可调用函数是否失败。
$password = 'secret'; Retry::onCondition('getInput', function($result) use ($password) { return $result === $password; }, 3);
传递参数
如果您使用函数或类/对象方法作为可调用函数并需要传递参数,则可以封装闭包调用。
private function multiply($a, $b) { return $a * $b; } ... $x = 3; $y = 4; Retry::onFailure(function() use ($x, $y) { return $this->multiply($x, $y); }, 3);
延迟策略
Retry 在两个有效负载调用之间睡眠。有多个策略可用于确定延迟的时间长度。所有延迟策略的数值都解释为毫秒(ms)。
恒定睡眠值
// sleep 2000 milliseconds (i.e. 2 seconds) between attempts $policy = new ConstantDelayPolicy(2000);
线性增加睡眠值
// sleep 1 second after the first, 2 after the second, 3 after the third... $policy = new LinearDelayPolicy(1000);
指数增加睡眠值
// sleep 1, 2, 4, 8, 16, ... $policy = new ExponentialDelayPolicy(1000); // sleep 1, 3, 9, 27, ... $policy = new ExponentialDelayPolicy(1000, 3);
固定序列的睡眠值
// sleep 2, 2, 4, 20, 20, 20, 20 ... (stick to last value after series has ended) $policy = new SeriesDelayPolicy([2000, 2000, 4000, 20000]); // sleep 2, 2, 4, 20, 2, 2, 4, 20, 2, 2, 4, ... (repeat series after it has ended) $policy = new SeriesDelayPolicy([2000, 2000, 4000, 20000], true);
带随机抖动的睡眠
// sleep a random amount between 1900 and 2100 milliseconds $policy = new JitterDelayPolicy(2000, 100);
无睡眠
// don't sleep at all $policy = new NoneDelayPolicy();
高级功能
省略延迟策略
如果您不想在尝试之间有任何延迟,可以使用上面描述的 NoneDelayPolicy
,传递 NULL
作为延迟策略,或者完全不传递延迟策略参数。
// retry without delay Retry::onFailure('myfunc', 3);
获取尝试次数
如果您需要获取成功有效负载调用所需的尝试次数,例如用于日志记录目的,可以将变量通过引用传递给 onFailure()
、onException()
和 onCondition()
方法。
Retry::onFailure('myfunc', 3, null, $tries); print "success after {$tries} attempts";
中止重试循环
要中止重试循环而不发出“成功”信号,可以在有效负载函数内部抛出 AbortException
。