tebru/executioner

提供一个库,用于在需要重试执行时处理 PHP 异常。

v0.4.1 2015-01-12 19:05 UTC

This package is auto-updated.

Last update: 2024-09-24 11:51:05 UTC


README

Build Status

Executioner

这个库旨在提供一个简单的方式来执行可能会抛出异常并需要重试的代码。

安装

运行 composer require tebru/executioner:dev-master

基本用法

该库可以这样使用

<?php

use Tebru\Executioner;

$executor = new Executor();
$result = $executor->execute(2, function () { /* code that may throw an exception */ });

这将在所有异常上重试两次。如果没有抛出异常而执行失败,将抛出 \Tebru\Executioner\Exception\FailedException。如果您不希望异常传播,请确保将 execute() 调用包裹在 try/catch 中。

事件

事件用于提供操作钩子和洞察。有 4 个事件:

  • beforeAttempt
  • afterAttempt
  • failedAttempt
  • endAttempt

此库使用 Symfony2 事件调度器。您可以自由使用包含的订阅者或创建自己的订阅者。

使用 Executor 上的监听器方法来定位一个事件,使用订阅者来定位多个事件。

尝试之间的延迟

<?php

use Tebru\Executioner;
use Tebru\Executioner\Subscriber\WaitSubscriber;

$waitStrategy = new \Tebru\Executioner\Strategy\WaitStrategy();

$executor = new Executor();
$executor->addSubscriber(new WaitSubscriber($waitStrategy));
$result = $executor->execute(2, function () { /* code that may throw an exception */ });

包含两种等待策略

  • Tebru\Executioner\Strategy\StaticWaitStrategy -- 在每次尝试之间等待固定的时间量
  • Tebru\Executioner\Strategy\ExponentialBackoffStrategy -- 平均而言,在每次尝试之间指数级等待更长的时间

日志记录

<?php

use Tebru\Executioner;
use Tebru\Executioner\Subscriber\LoggerSubscriber;

$logger = new \Psr\Log\LoggerInterface(); // the only requirement is you need a ps-3 compatible logger

$executor = new Executor();
$executor->addSubscriber(new LoggerSubscriber('name-of-this-logger-to-distinguish-it-in-the-logs', $logger));
$result = $executor->execute(2, function () { /* code that may throw an exception */ });

非异常重试

<?php

use Tebru\Executioner;
use Tebru\Executioner\Subscriber\ReturnSubscriber;

$executor = new Executor();
$executor->addSubscriber(new ReturnSubscriber([false]));
$result = $executor->execute(2, function () { return false; });

快捷方式

为了使生活更轻松,有一些辅助方法可以创建一些包含的订阅者

添加一个 LoggerSubscriber

Executor::addLogger($name, LoggerInterface $logger)

使用 StaticWaitStrategy 添加一个 WaitSubscriber

Executor::addWait($seconds)

添加一个 WaitSubscriber

Executor::addWaitStrategy(WaitStrategy $waitStrategy)