diephp/perhaps

捕获和重试代码执行

v1.0.2 2024-05-24 18:52 UTC

This package is auto-updated.

Last update: 2024-09-27 13:56:29 UTC


README

Total Downloads Latest Stable Version License

Perhaps 重试库

一个 Laravel 包,提供了一种简单的方法来重试任何逻辑,具有可自定义的尝试次数和延迟。这在某些操作可能因临时问题(如网络错误或临时服务中断)而失败的情况下特别有用。

安装

  1. 通过 Composer 安装包

    composer require diephp/perhaps
  2. 在您的 config/app.php 文件中注册服务提供者

    'providers' => [
        // ...
        \DiePHP\Perhaps\Providers\PerhapsServiceProvider::class,
    ],

    或者对于 Laravel 11+,将提供者添加到 bootstrap/providers.php 中的列表

    return [
        App\Providers\AppServiceProvider::class,
        ...
        \DiePHP\Perhaps\Providers\PerhapsServiceProvider::class,
    ];
  3. 可选地,发布包配置

    php artisan vendor:publish --tag=perhaps

用法

基本用法

此包提供的主要功能是 Perhaps::retry。您可以使用它来重试指定次数的任何逻辑。

use DiePHP\Perhaps\Facades\Perhaps;

Perhaps::retry(function() {
    // Your logic here
}, 3); // Retry 3 times

处理延迟

您还可以使用 Traversable 迭代器指定延迟序列。这允许您在重试之间定义自定义延迟逻辑。您可以在此处查看详细信息:[https://github.com/diephp/sequences](https://github.com/diephp/sequences)

use DiePHP\Perhaps\Facades\Perhaps;
use DiePHP\Sequences\ProgressiveSequence;

Perhaps::retry(function() {
    // Your logic here
}, 10, new ProgressiveSequence(1000000, 100)); // Retry 10 times with progressive delay
use DiePHP\Perhaps\Facades\Perhaps;
use DiePHP\Sequences\RandSequence;

Perhaps::retry(function() {
    // Your logic here
}, 10, new RandSequence(1000000, 90000000));
use DiePHP\Perhaps\Facades\Perhaps;
use DiePHP\Sequences\ExponentialSequence;

Perhaps::retry(function() {
    // Your logic here
}, 1000, new ExponentialSequence(10, 100));

带有异常处理的示例

在此示例中,重试逻辑将处理异常并记录重试尝试。

Perhaps::retry(function($attempt) {
    if ($attempt < 3) {
        throw new \Exception("Simulated failure");
    }
    // Successful operation
    echo "Success on attempt $attempt";
}, 5); // Retry 5 times

配置

您可以通过修改发布的配置文件 config/perhaps.php 来配置此包。这允许您自定义日志记录和异常处理行为。

许可证

此包是开源软件,根据 MIT 许可证 许可。

重点

  • retry 方法允许您重试任何可调用逻辑指定次数。
  • 您可以在重试之间指定延迟序列以定义自定义延迟逻辑。
  • 注册服务提供者并可选地发布配置以进行自定义。
  • 使用提供的门面以方便地访问您的 Laravel 应用程序中的 retry 方法。