tobion / retry
一个通用的库,用于在发生错误时重试操作。您可以配置行为,例如要重试的异常。
v1.0.0
2019-09-19 14:30 UTC
Requires
- php: >=7.1
Requires (Dev)
- phpunit/phpunit: ^7.5
This package is auto-updated.
Last update: 2024-08-29 00:54:02 UTC
README
用于在失败时重试代码的PHP库,例如HTTP请求或数据库事务。
安装
$ composer require tobion/retry
使用
use Tobion\Retry\Retry; $callableThatMightFail = function (int $arg1, int $arg2): int { if (random_int(1, 2) % 2) { throw new \RuntimeException('Sudden error'); } return $arg1 + $arg2; }; // Allows you to call the callable with parameters and retry its execution in case an exception is thrown. // You can access the return value of the callable (3 in this case). $returnValue = Retry::configure()->call($callableThatMightFail, 1, 2); // By default: // - The callable is retried twice (i.e. max three executions). If it still fails, the last error is rethrown. // - Retries have a no delay between them. // - Every \Throwable will trigger the retry logic, i.e. both \Exception and \Error. // You can adjust the retry logic like this: $retryingCallable = Retry::configure() ->maxRetries(5) ->delayInMs(100) ->retryOnSpecificExceptions(\RuntimeException::class) // other failures like \TypeError will not be retried ->decorate($callableThatMightFail) ; $returnValue = $retryingCallable(1, 2); // $retryingCallable just decorates the original callable and can be used like it. // To find out how often it had to retry, you can use: $retryingCallable->getRetries();
贡献
运行测试
$ composer install
$ vendor/bin/simple-phpunit