You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel8动态多租户多数据库系统中运行artisan queue:work命令

Laravel 8 多租户独立数据库队列处理解决方案

方案1:自定义Artisan命令实现单命令批量启动租户队列

适合本地测试、租户数量较少的场景:

  • 执行命令生成自定义控制台命令:php artisan make:command TenantQueueWorkCommand
  • 编辑生成的app/Console/Commands/TenantQueueWorkCommand.php文件,参考逻辑如下:
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class TenantQueueWorkCommand extends Command
{
    protected $signature = 'tenant:queue:work {tenant?}';
    protected $description = '为指定/所有租户启动队列工作进程';

    // 你存储所有子域名的数组,也可以从数据库/配置文件读取
    protected $tenants = ['foo', 'bar', 'baz'];

    public function handle()
    {
        $targetTenant = $this->argument('tenant');
        $processTenants = $targetTenant ? [$targetTenant] : $this->tenants;

        foreach ($processTenants as $tenant) {
            // 动态配置租户数据库连接,参数复用你原有的租户连接配置
            config([
                'database.connections.tenant.database' => $tenant,
            ]);
            DB::purge('tenant');
            DB::reconnect('tenant');

            // 调用原生queue:work命令,绑定当前租户的数据库连接
            $this->info("启动租户 {$tenant} 的队列进程");
            $this->call('queue:work', [
                '--connection' => 'tenant',
                '--daemon' => true,
                '--tries' => 3,
            ]);
        }
    }
}
  • 配置完成后,执行php artisan tenant:queue:work即可批量启动所有租户的队列进程,也可指定单个租户执行php artisan tenant:queue:work foo单独启动对应租户的队列。

方案2:Supervisor 托管租户队列(生产环境推荐)

生产环境下手动启动的进程存在异常退出无法自动恢复的问题,推荐用Supervisor管理所有租户的队列进程:

  • 首先在config/queue.php中提前配置租户专用的队列连接:
return [
    // 其他配置
    'connections' => [
        // 其他连接
        'tenant' => [
            'driver' => 'database',
            'connection' => 'tenant', // 对应config/database.php中的租户数据库连接名
            'queue' => 'default',
            'retry_after' => 90,
        ],
    ],
];
  • 批量生成Supervisor配置,每个租户对应独立的进程配置,示例配置如下:
[program:tenant-queue-foo]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/your-project/artisan queue:work tenant --tenant=foo
autostart=true
autorestart=true
user=www-data
numprocs=1
redirect_stderr=true
stdout_logfile=/var/www/your-project/storage/logs/tenant-foo-queue.log
  • 所有租户配置写入Supervisor配置目录后,执行supervisorctl reread、supervisorctl update即可批量启动所有租户的队列进程,进程异常退出后会自动重启。

补充优化方案

如果租户数量超过50个,服务器无法支撑这么多独立进程,可以修改任务投递逻辑,在所有任务中存入租户标识,共用同一个中心队列,消费时根据任务中的租户标识动态切换数据库连接,可大幅降低资源占用。

内容的提问来源于stack exchange,提问作者Bijoy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 17:06:03