nevsnode/backoff

简单的PHP回退库

v1.3.0 2018-07-11 08:28 UTC

This package is not auto-updated.

Last update: 2024-09-26 15:51:14 UTC


README

非常简单的回退PHP库。它提供了一种简单的解决方案,在失败后等待递增延迟。

安装

composer require nevsnode/backoff

示例用法

<?php
use nevsnode\Backoff;

$backoff = new Backoff();

$resource = new ExampleResource();
$result = $backoff->retryOnException(5, function () use ($resource) {
    $return = $resource->fetchSomething();
    if (!$return) {
        throw new Exception('Failed to fetch something');
    }
    return $return;
});

默认情况下,当超过重试次数时,最后一次异常将再次抛出。可以定义一个最终的闭包/值,用于执行或返回

<?php
$backoff = new nevsnode\Backoff();

// $result will now become the string "Some error"
$result = $backoff->retryOnException(3, function () {
    throw new \Exception('Some error');
}, function ($e) {
    return $e->getMessage();
});

// $result will now become FALSE
$result = $backoff->retryOnException(2, function () {
    throw new \Exception('Some error');
}, false);

设置

设置可以作为关联数组传递给构造函数,并在实例化后返回或调整

<?php

// pass settings to constructor
$backoff = new Backoff([
    'min' => 2000,
    'max' => 10000,
    'factor' => M_E,
]);

// define setting through setter
$backoff->setJitter(true);
$backoff->setJitterMax(6000);
$backoff->setMin(3000);

// return setting through getter
$max = $backoff->getMax();