uocnv/laravel-queue-monitor

Laravel 数据库作业队列监控

1.0 2024-03-22 06:33 UTC

This package is auto-updated.

Last update: 2024-09-29 06:09:13 UTC


README

Latest Stable Version Total Downloads License GitHub Build Status

本包提供与 Laravel Horizon 类似的数据库队列监控功能。

功能

  • 监控任何队列中的作业,就像 Laravel Horizon 一样
  • 处理失败作业并存储异常
  • 监控作业进度
  • 获取作业剩余时间的估计值
  • 为作业监控存储附加数据
  • 通过 UI 重试作业

安装

composer require romanzipp/laravel-queue-monitor

还有一个针对 Laravel Nova 资源和指标的支持包 romanzipp/Laravel-Queue-Monitor-Nova

升级

✨ 如果你正在更新到 5.0,请参阅 升级指南

配置

将配置和迁移复制到你的项目中

php artisan vendor:publish --provider="romanzipp\QueueMonitor\Providers\QueueMonitorProvider" --tag=config --tag=migrations

迁移 Queue Monitoring 表。表名可以在配置文件或发布的迁移中进行配置。

php artisan migrate

使用

要监控作业,只需添加 romanzipp\QueueMonitor\Traits\IsMonitored 特性。

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use romanzipp\QueueMonitor\Traits\IsMonitored; // <---

class ExampleJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;
    use IsMonitored; // <---
}

重要! 你需要在你的作业类中实现 Illuminate\Contracts\Queue\ShouldQueue 接口。否则,Laravel 不会分发包含监控作业状态信息的任何事件。

Web 界面

你可以通过将 ui.enabled 设置为 true 来启用 Web UI。

发布前端资源

php artisan vendor:publish --provider="romanzipp\QueueMonitor\Providers\QueueMonitorProvider" --tag=assets

有关更多信息,请参阅 完整的配置文件

Preview Preview

命令

artisan queue-monitor:stale

此命令将旧的监控条目标记为 stale。你应该定期在你的控制台内核中运行此命令。

参数和选项

  • --before={date} 所有条目将被标记为 stale 的开始日期
  • --beforeDays={days} 所有条目将被标记为 stale 的相对天数
  • --beforeInterval={interval} 在此之前条目将被标记为 stale 的日期间隔
  • --dry 仅进行 dry-run

artisan queue-monitor:purge

此命令删除旧的监控模型。

参数和选项

  • --before={date} 在此之前删除所有条目的开始日期
  • --beforeDays={days} 在此之前删除条目的相对天数
  • --beforeInterval={interval} 在此之前删除条目的日期间隔
  • --queue={queue} 只删除特定队列(逗号分隔值)
  • --only-succeeded 只删除成功条目
  • --dry 仅进行 dry-run

需要提供 beforebeforeDate 参数之一。

高级用法

进度

你可以设置一个 进度值(0-100)来获取作业进度的估计。

use Illuminate\Contracts\Queue\ShouldQueue;
use romanzipp\QueueMonitor\Traits\IsMonitored;

class ExampleJob implements ShouldQueue
{
    use IsMonitored;

    public function handle()
    {
        $this->queueProgress(0);

        // Do something...

        $this->queueProgress(50);

        // Do something...

        $this->queueProgress(100);
    }
}

块进度

作业的常见场景是遍历大型集合。

此示例作业遍历大量用户,并在每个块迭代时更新其进度值。

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Collection;
use romanzipp\QueueMonitor\Traits\IsMonitored;

class ChunkJob implements ShouldQueue
{
    use IsMonitored;

    public function handle()
    {
        $usersCount = User::count();

        $perChunk = 50;

        User::query()
            ->chunk($perChunk, function (Collection $users) use ($perChunk, $usersCount) {

                $this->queueProgressChunk($usersCount‚ $perChunk);

                foreach ($users as $user) {
                    // ...
                }
            });
    }
}

进度冷却

为了避免频繁重复的更新查询使数据库过载,您可以设置并覆盖 progressCooldown 方法,并指定在将进度更新写入数据库之前等待的秒数。请注意,对于值 0、25、50、75 和 100,冷却时间将被忽略。

use Illuminate\Contracts\Queue\ShouldQueue;
use romanzipp\QueueMonitor\Traits\IsMonitored;

class LazyJob implements ShouldQueue
{
    use IsMonitored;

    public function progressCooldown(): int
    {
        return 10; // Wait 10 seconds between each progress update
    }
}

自定义数据

此包还允许在监控模型上使用数组语法设置自定义数据。

use Illuminate\Contracts\Queue\ShouldQueue;
use romanzipp\QueueMonitor\Traits\IsMonitored;

class CustomDataJob implements ShouldQueue
{
    use IsMonitored;

    public function handle()
    {
        $this->queueData(['foo' => 'Bar']);
        
        // WARNING! This is overriding the monitoring data
        $this->queueData(['bar' => 'Foo']);

        // To preserve previous data and merge the given payload, set the $merge parameter true
        $this->queueData(['bar' => 'Foo'], true);
    }
}

为了在 UI 上显示自定义数据,您需要在 config/queue-monitor.php 下的这一行添加内容

'ui' => [
    ...

    'show_custom_data' => true,

    ...
]

初始数据

此包还允许设置在作业排队时设置的初始数据。

use Illuminate\Contracts\Queue\ShouldQueue;
use romanzipp\QueueMonitor\Traits\IsMonitored;

class InitialDataJob implements ShouldQueue
{
    use IsMonitored;
    
    public function __construct(private $channel)
    {
    }

    public function initialMonitorData()
    {
        return ['channel_id' => $this->channel];
    }
}

仅保留失败作业

您可以覆盖 keepMonitorOnSuccess() 方法,仅存储已执行作业的失败监控条目。如果您只想保留频繁执行但值得监控的失败的监控,则可以使用此方法。或者,您也可以使用 Laravel 内置的 failed_jobs 表。

use Illuminate\Contracts\Queue\ShouldQueue;
use romanzipp\QueueMonitor\Traits\IsMonitored;

class FrequentSucceedingJob implements ShouldQueue
{
    use IsMonitored;

    public static function keepMonitorOnSuccess(): bool
    {
        return false;
    }
}

检索已处理作业

use romanzipp\QueueMonitor\Models\Monitor;

$job = Monitor::query()->first();

// Check the current state of a job
$job->isFinished();
$job->hasFailed();
$job->hasSucceeded();

// Exact start & finish dates with milliseconds
$job->getStartedAtExact();
$job->getFinishedAtExact();

// If the job is still running, get the estimated seconds remaining
// Notice: This requires a progress to be set
$job->getRemainingSeconds();
$job->getRemainingInterval(); // Carbon\CarbonInterval

// Retrieve any data that has been set while execution
$job->getData();

// Get the base name of the executed job
$job->getBasename();

模型作用域

use romanzipp\QueueMonitor\Models\Monitor;

// Filter by Status
Monitor::failed();
Monitor::succeeded();

// Filter by Date
Monitor::lastHour();
Monitor::today();

// Chain Scopes
Monitor::today()->failed();

测试

在本地执行测试的最简单方法是使用 Lando。自动启动应用程序和数据库容器的 Lando 配置文件

lando start

lando phpunit-sqlite
lando phpunit-mysql
lando phpunit-postgres

升级

许可证

MIT 许可证 (MIT)。有关更多信息,请参阅 许可证文件

此包受 gilbitron 的 laravel-queue-monitor 启发,该库不再维护。

Star History Chart