Skip to content

队列

租户包会把 config/tenancy.php 中的 centraltenant 两个 database 队列连接合并到 Laravel 的 queue.connections。应用默认连接仍由 QUEUE_CONNECTION 决定,租户包不会修改它。

连接默认队列用途
centraldefault中央任务,payload 不携带租户标识
tenanttenant租户任务,payload 携带当前租户的 tenant_id

central 连接配置了 central => true。即使中央任务在租户上下文中派发,Stancl 也不会向该连接的 payload 写入租户标识。

创建租户任务

shell
php artisan catch:tenant:job TenancyTest

命令在 app/Jobs 生成 App\Jobs\TenancyTest。普通 queued Stub 需要显式选择 tenant 连接:

php
<?php

namespace App\Jobs;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

class TenancyTest implements ShouldQueue
{
    use Queueable;

    public function __construct()
    {
        $this->onConnection('tenant');
    }

    public function handle(): void
    {
        // 这里已经恢复派发任务时的租户上下文。
    }
}

批处理任务使用 --batched 生成,当前 Stub 已在构造函数中调用 $this->onConnection('tenant')

shell
php artisan catch:tenant:job TenancyImport --batched

同步任务使用 --sync,它不会进入队列:

shell
php artisan catch:tenant:job TenancyReport --sync

租户任务必须在已初始化的租户上下文中派发。Stancl 会把租户 UUID 写入 payload 的 tenant_id,worker 处理任务前据此恢复数据库、缓存、文件系统和日志上下文,任务结束后恢复中央上下文。

启动 Worker

中央任务和租户任务分别消费对应连接与队列:

shell
# 中央队列
php artisan queue:work central --queue=default

# 租户队列
php artisan queue:work tenant --queue=tenant

生产环境使用 Supervisor、systemd 等进程管理器分别守护两个 worker。发布代码后执行 php artisan queue:restart,让常驻 worker 平滑加载新代码和配置。

队列监控

开启监控:

dotenv
TENANCY_QUEUE_MONITOR=true

只有使用 Modules\Tenancy\Support\Queue\QueueMonitor trait 的 Job 才会写入监控记录:

php
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Modules\Tenancy\Support\Queue\QueueMonitor;

class TenancyImport implements ShouldQueue
{
    use Queueable, QueueMonitor;

    public function handle(): void
    {
        $this->queueProgress(25);

        // 执行业务逻辑……

        $this->queueProgress(100);
    }
}

监控数据统一写入中央数据库的 job_queue_monitor 表,租户数据库无需创建该表。页面提供以下信息:

  • 中央任务与租户任务的执行范围,租户任务按 tenant_uuid 筛选。
  • 等待、进行中、成功、失败和过期状态。
  • 当前尝试次数、重试标记、开始和结束时间。
  • queueProgress()queueProgressChunk() 写入的执行进度。
  • 失败任务的异常类型、异常消息和堆栈。

keepMonitorOnSuccess() 默认返回 true。高频 Job 可以覆盖该方法并返回 false,只保留失败记录:

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

修改 TENANCY_QUEUE_MONITOR 后需要重建配置缓存并重启 worker:

shell
php artisan config:clear
php artisan config:cache
php artisan queue:restart