MongoDB 队列驱动实战:laravel-mongodb 的任务调度、失败处理与 Job 批处理完全指南

原创2026-10-14 16:55:051,357 阅读
文章标签:后端数据库

MongoDB 队列驱动实战:laravel-mongodb 的任务调度、失败处理与 Job 批处理完全指南

导读

mongodb/laravel-mongodb 不仅为 Eloquent 模型与查询构造器提供 MongoDB 支持,还内置了一套完整的队列驱动(mongodb queue driver):它复用 Laravel 的 DatabaseQueue 语义,将 jobs 集合作为任务存储,并通过 findOneAndUpdate 原子操作保证多 Worker 并发消费下不重复取任务。本文以 队列参考文档 为主体,结合 src/Queue 与 src/Bus/MongoBatchRepository.php 的源码实现,系统讲解从 config/queue.php 配置、索引建立、任务分发、Worker 运行,到失败任务记录与 Job 批处理(Batching)的完整链路。读完本文,你将掌握在 Laravel + MongoDB 项目里落地一套高可用、可观测、支持批量任务的队列系统。

一、队列驱动在 laravel-mongodb 中的角色

laravel-mongodb 的队列方案走的是「兼容 Laravel DatabaseQueue」的路线:核心类 MongoQueue 直接继承 Illuminate\Queue\DatabaseQueue,因此任务生命周期(push / pop / release / delete / failed)与 Laravel 原生数据库队列完全一致,开发者无需学习新概念,只多了一层 MongoDB 的连接与集合映射。接入入口位于 MongoDBServiceProvider.php:包在解析 queue 容器时通过 $queue->addConnector('mongodb', ...) 注册 mongodb 连接器,因此只要在 config/queue.php 中把某连接的 driver 设为 mongodb,Laravel 的 queue:work、queue:retry 等命令即可直接使用。

二、config/queue.php 完整配置与参数解析

2.1 完整配置骨架

以下配置取自 队列参考文档,可直接作为项目 config/queue.php 的基准:

<?php

return [
    'default' => env('QUEUE_CONNECTION', 'mongodb'),

    'connections' => [
        'mongodb' => [
            'driver'       => 'mongodb',
            'connection'   => 'mongodb',  // name from config/database.php
            'collection'   => 'jobs',
            'queue'        => 'default',
            'retry_after'  => 90,
            'after_commit' => false,      // set true when dispatching inside DB::transaction()
        ],
    ],

    'failed' => [
        'driver'   => 'mongodb',
        'database' => 'mongodb',
        'table'    => 'failed_jobs',  // use 'table' not 'collection' — Laravel reads this key
    ],

    // Job batching — requires MongoDBBusServiceProvider
    'batching' => [
        'database'   => 'mongodb',
        'collection' => 'job_batches',
    ],
];

2.2 connections.mongodb 参数逐项说明

连接器在 MongoConnector::connect() 中解析这些参数,各项含义与默认值如下:

参数 含义 默认值 说明
driver 连接器名称 — 必须为 mongodb,用于命中 MongoDBServiceProvider 注册的连接器
connection 数据库连接名 null(默认连接) 指 config/database.php 中定义的 MongoDB 连接名,与队列连接名是两个概念
collection 存储任务的集合 jobs 源码中 $config['collection'] ?? 'jobs' 兜底
queue 默认队列名 default 源码中 $config['queue'] ?? 'default' 兜底
retry_after 任务预留超时(秒) 60 示例中设为 90;不设置时连接器默认 60,对应 MongoQueue 的 $retryAfter 属性
after_commit 是否在数据库事务提交后才入队 false 在 DB::transaction() 内分发任务时建议设为 true,避免任务在事务回滚前被 Worker 提前消费

注意:retry_after 与 expire 的历史命名。自包版本 4.4 起,若配置使用 table 或 expire 键,MongoConnector 会触发 E_USER_DEPRECATED 弃用警告,并自动将其映射到 collection / retry_after。新项目请直接使用 collection 与 retry_after。

2.3 failed 失败任务配置

失败任务沿用 Laravel 的标准键结构:database 指向存储失败记录的 MongoDB 连接名,table 指定 failed_jobs 集合。这里的关键坑是 必须使用 table 键而不是 collection——Laravel 的 queue.failer 服务解析的是 queue.failed.table 这一固定键,MongoConnector 的 table→collection 兼容逻辑只作用于 connections.* 段,不会作用于 failed 段。

2.4 batching 批处理配置与服务提供者注册

Job 批处理需要额外的仓储支持,配置段指定 database(MongoDB 连接名)与 collection(默认 job_batches)。同时必须在 bootstrap/providers.php 中注册 MongoDB\Laravel\MongoDBBusServiceProvider::class:

// bootstrap/providers.php
return [
    MongoDB\Laravel\MongoDBServiceProvider::class,
    MongoDB\Laravel\MongoDBBusServiceProvider::class,
    // ...
];

src/MongoDBBusServiceProvider.php 的注册逻辑如下:

  • 按 queue.batching.database 解析连接,若该连接不是 MongoDB\Laravel\Connection 实例则抛出 InvalidArgumentException,提示批处理驱动必须配 MongoDB 连接;
  • 按 queue.batching.collection(默认 job_batches)构造 MongoBatchRepository;
  • 读取 queue.batching.driver,当值为 mongodb 时通过 extend 用 MongoBatchRepository 替换 Laravel 默认的 BatchRepository。也就是说,若你的配置中缺少 driver => 'mongodb',批处理将回落到 Laravel 的 database 驱动,需要留意。

补充:包已在 composer.json 的 extra.laravel.providers 中声明了上述两个 Provider,使用 Laravel 包自动发现机制时通常无需手动注册;显式写入 bootstrap/providers.php 则适用于关闭自动发现或追求显式声明的场景。此外 composer.json 声明了与 illuminate/bus < 10.37.2 的版本冲突,批处理功能依赖较新的 Bus 组件。

三、必备索引:让 MongoDB 队列高效查询

MongoDB 的队列查询本质上仍是集合扫描 + 排序,缺索引会导致 queue:work 性能急剧下降。参考文档给出的建索引导入迁移:

Schema::connection('mongodb')->create('jobs', function (Blueprint $collection): void {
    $collection->index(['queue' => 1, 'reserved' => 1, 'available_at' => 1]);
    $collection->index('reserved_at');
});

Schema::connection('mongodb')->create('failed_jobs', function (Blueprint $collection): void {
    $collection->unique('uuid');
    $collection->index('failed_at');
});

这些索引并非凭空建议,而是精确对应 MongoQueue 的查询模式:

索引 支撑的查询 源码位置
{queue: 1, reserved: 1, available_at: 1} 取任务时按 queue 过滤、reserved != 1 过滤、available_at <= now 过滤并按 available_at 升序排序 getNextAvailableJobAndReserve()
reserved_at 单键索引 超时释放时 whereNotNull('reserved_at')->where('reserved_at', '<=', $expiration) releaseJobsThatHaveBeenReservedTooLong()
uuid 唯一索引 Laravel 失败任务表依赖 uuid 标识记录,防止重复写入 DatabaseFailedJobProviderTest 中 failed_jobs 文档含 _id / failed_at 等字段
failed_at 索引 queue:prune-failed / flush 等按时间清理失败记录 DatabaseFailedJobProviderTest.php 的 prune()

迁移可单独指定连接执行:php artisan migrate --database=mongodb,确保索引建立在目标 MongoDB 数据库上。

四、分发任务与启动 Worker

4.1 分发到指定连接与队列

参考文档的用法是将任务显式投递到 MongoDB 队列,并附上要使用的队列名:

IndexPostJob::dispatch((string) $post->_id)
    ->onConnection('mongodb')
    ->onQueue('indexing');
  • onConnection('mongodb') 指定使用 config/queue.php 中的 mongodb 队列连接;
  • onQueue('indexing') 指定任务落入 jobs 集合中 queue = "indexing" 的任务分支,可据此实现业务级隔离。

4.2 Worker 与失败任务管理命令

php artisan queue:work mongodb --queue=indexing
php artisan queue:failed
php artisan queue:retry all
  • queue:work mongodb:以 mongodb 连接启动常驻 Worker,--queue=indexing 限定只消费该队列;
  • queue:failed:列出 failed_jobs 中的失败任务;
  • queue:retry all:将全部失败任务重新入队(也可用具体 ID 定向重试)。

其余 Laravel 原生队列命令(如 queue:restart、queue:monitor、queue:prune-failed、queue:prune-batches)同样可用;其中 queue:prune-batches 之所以生效,正是因为 MongoBatchRepository 实现了 PrunableBatchRepository 接口(见第八节)。

五、编写 Job 类:只传字符串 ID,不要传 ObjectId

参考文档给出了规范的 Job 类模板:

<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

final class IndexPostJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $tries   = 3;
    public int $timeout = 60;

    public function __construct(public readonly string $postId) {}
    // Pass string IDs, never ObjectId instances — they must serialize cleanly.

    public function handle(): void
    {
        // ...
    }
}

要点解析:

  • tries 与 timeout:tries = 3 限制最大尝试次数,timeout = 60 限制单次执行秒数;二者都会写入任务 payload 的 maxTries / timeout 字段,由 Worker 强制执行(可参考 tests/QueueTest.php 中对 payload 字段的断言)。
  • 只传字符串 ID:__construct 接收 (string) $post->_id。原因有二:
    1. 使用 SerializesModels 时,任务 payload 会被序列化存储;直接传入 MongoDB\BSON\ObjectId 实例容易在序列化/反序列化边界产生类型或 BSON 兼容问题,而字符串 ID 可以干净地序列化;
    2. 在 Eloquent 层,MongoDB 模型的主键 _id 对外暴露时通常应视为字符串(模型用 (string) $this->_id 输出),API 资源与队列负载保持一致,避免类型漂移。技能库 SKILL.md 的约束也强调在 API 资源中将 _id 转为字符串。
  • handle() 内再按 ID 取模型:例如 Post::query()->where('_id', $this->postId)->first(),不要在构造时传入整个模型实例,以免把过期的模型状态快照带进队列。

六、底层原理:findOneAndUpdate 原子预留与超时释放

6.1 pop:一条 findOneAndUpdate 完成「取件 + 锁定」

MongoQueue::pop() 的处理流程是:先按 retryAfter 清理超时任务,再调用 getNextAvailableJobAndReserve() 取下一个可用任务。核心的原子操作位于 getNextAvailableJobAndReserve():

$job = $this->database->getCollection($this->table)->findOneAndUpdate(
    [
        'queue'        => $this->getQueue($queue),
        'reserved'     => ['$ne' => 1],
        'available_at' => ['$lte' => $now],
    ],
    [
        '$set' => ['reserved' => 1, 'reserved_at' => $now],
        '$inc' => ['attempts' => 1],
    ],
    [
        'returnDocument' => FindOneAndUpdate::RETURN_DOCUMENT_AFTER,
        'sort'           => ['available_at' => 1],
    ],
);

这段代码同时解决了 Laravel 数据库队列最经典的竞态问题:多个 Worker 并发 pop 时,可能同时读到同一条任务记录。通过 findOneAndUpdate 的原子语义,「按条件筛选 + 原地标记 reserved = 1 + 递增 attempts」在单次操作内完成,读到的记录必然是已锁定给自己的记录,不会重复消费。sort: available_at: 1 保证严格按可执行时间先到先取,配合第二、三节的复合索引 {queue, reserved, available_at} 构成高效查询。取回后还会把 _id 映射为 id 字段,与 Laravel DatabaseJob 的字段约定对齐。

6.2 超时释放:reserved 太久未完成的任务重新入队

releaseJobsThatHaveBeenReservedTooLong() 以 retryAfter 为阈值:凡 reserved_at 早于 now - retryAfter 且仍处于预留状态的任务,通过 releaseJob() 重置为 reserved = 0、reserved_at = null,并保留已累计的 attempts 值,使任务可被再次消费。这正是 retry_after 参数的核心语义——它既是 Worker 崩溃/卡死后的兜底恢复机制,也是防止任务被无限重试的节流器。

6.3 完成、删除与重试

  • deleteReserved():按 _id 删除已预留任务(任务成功执行后调用);
  • deleteAndRelease():删除当前预留记录并按延迟重新入队(用于需要「换新身份」的重试场景);
  • MongoJob 继承 DatabaseJob,额外暴露 isReserved() 与 reservedAt(),分别读取文档中的 reserved 布尔值与 reserved_at 时间戳。

上述行为均有测试覆盖:见 tests/QueueTest.php 中的 testQueueJobLifeCycle(预留状态、payload 字段)、testQueueJobExpired(超时任务被重新取出且 attempts 递增)、testIncrementAttempts(未取出的任务 attempts 保持为 0)、testJobRelease(释放后 attempts = 1)、testQueueRelease(延迟时间写入 available_at)等用例。

七、失败任务:failed_jobs 与 Laravel 命令天然兼容

失败任务存储不需要额外的自定义驱动——Laravel 自带的 DatabaseFailedJobProvider 可以直接跑在 MongoDB 连接上。这一点由测试 tests/Queue/Failed/DatabaseFailedJobProviderTest.php 明确验证:log()、count()、all()、find()、forget()、ids()、flush()、prune() 全链路可用。

与关系型数据库的唯一差异在 ID 形态:失败记录的 id 是 MongoDB 的 ObjectId(测试断言 assertInstanceOf(ObjectId::class, $inserted->id)),而 queue:retry 等命令按字符串 ID 操作时,字符串与 ObjectId 的互转由 Laravel 的 MongoDB 查询构造器透明处理,因此在命令行中依旧可以直接使用 ID 字符串(例如 php artisan queue:retry <id>)。这要求 failed_jobs 集合保持第二、三节所述索引:uuid 唯一索引防止记录重复、failed_at 索引支撑 prune() 的按时间批量清理。

八、Job Batching:把 MongoDB 变成批处理仓库

8.1 仓储与回调模型

注册 MongoDBBusServiceProvider 后,Laravel 的 Bus::batch()、PendingBatch、Batch::then/after/catch/finally 等批处理 API 即可工作。批处理元数据存放在 job_batches 集合,由 MongoBatchRepository 实现,其关键设计如下:

行为 实现要点 源码位置
批次 ID 直接使用 MongoDB _id(ObjectId),对外是字符串;查找时 new ObjectId($batchId) 转换 find()
创建批次 store() 初始化 total_jobs / pending_jobs / failed_jobs 计数,options 用 serialize() 序列化(回调闭包必须序列化存储) store()
计数更新 用 findOneAndUpdate + $inc / $pull / $push 原子增减 pending_jobs、failed_jobs 与 failed_job_ids,并返回最新计数 decrementPendingJobs()、incrementFailedJobs()
完成/取消 markAsFinished() 写入 finished_at;cancel() 将 cancelled_at 与 finished_at 置为同一时间戳(有专门测试 testCancelSetsSameTimestampForCancelledAtAndFinishedAt 验证) markAsFinished()、cancel()
读取一致性 find() 使用 ReadPreference::PRIMARY,避免主从复制延迟导致「批次刚建好就查不到」的竞态 find()
清理 prune()(按 finished_at)、pruneUnfinished()(按 created_at)、pruneCancelled()(按 cancelled_at)支撑 queue:prune-batches 命令 prune 系列

8.2 批处理与事务的协同

MongoBatchRepository::transaction() 委托给 MongoDB 连接的事务能力,rollBack() 则先检查当前 session 是否在事务中再回滚——testRollBackWithoutSessionIsNoOp 专门验证了无活动 session 时 rollBack() 是安全的空操作。这意味着在复制集/分片集群环境下,批次元数据的更新可以纳入 MongoDB 事务,保证与业务数据的一致性(事务本身的前提条件见 transactions 参考文档)。

8.3 批处理的能力验证

tests/Bus/MongoBatchRepositoryTest.php 覆盖了批次的完整生命周期:批量添加任务并断言 totalJobs / pendingJobs、成功任务逐条记录后触发 progress / then / finally 回调、失败任务在 allowFailures 开关下的 catch 行为差异、批次取消与删除、then / catch / finally 回调组合(对应 Fixtures 中的 ChainHeadJob 等链式任务)等。这些用例全部运行在真实的 MongoDB 连接上,可作为你自建批处理逻辑时的对照参考。

九、验证清单与常见坑

9.1 上线前验证步骤

  1. 索引先行:执行迁移 php artisan migrate --database=mongodb,确认 jobs 与 failed_jobs 的索引已创建(见第三、二节);
  2. 配置自检:确认 connections.mongodb 使用 collection / retry_after 而非弃用的 table / expire;确认 failed 段使用 table 键;确认 batching.driver = 'mongodb' 且已注册 MongoDBBusServiceProvider;
  3. 端到端冒烟:分发一条任务 → php artisan queue:work mongodb --queue=indexing --once 消费 → 用 php artisan queue:failed 与 queue:retry all 验证失败链路。

9.2 高频问题排查

  • 任务被重复执行:retry_after 小于任务实际执行时长,Worker 尚未完成即触发超时释放。调大 retry_after,或按执行耗时预估设置。
  • Worker 变慢:检查 jobs 集合是否缺少 {queue, reserved, available_at} 复合索引——缺少索引时 findOneAndUpdate 会退化为全集合扫描。
  • 批处理不生效:多数是 batching.driver 未设为 mongodb,导致 BatchRepository 未被子类替换;或 MongoDBBusServiceProvider 未注册。
  • 序列化异常:任务负载中混入了 ObjectId 实例,改传 (string) $id 字符串(见第五、四节)。
  • 分发的任务与事务冲突:在 DB::transaction() 内分发时若任务不应在事务回滚前执行,将 after_commit 设为 true。

结语

从连接器注册、集合索引、原子取件,到失败任务与批处理仓储,laravel-mongodb 的队列能力完整复刻并适配了 Laravel 数据库队列的全部心智模型,同时把 MongoDB 的原生优势——findOneAndUpdate 原子操作、ObjectId 原生 ID、ReadPreference 一致性控制、PrunableBatchRepository 的清理命令支持——融入其中。按本文配置索引、规范任务负载(字符串 ID)、正确设置 retry_after 与批处理驱动,即可在生产环境获得可靠且可观测的异步任务体系。相关实现与测试可在 src/Queue、src/Bus/MongoBatchRepository.php、tests/QueueTest.php 与 tests/Bus/MongoBatchRepositoryTest.php 中继续深入研读。

登录后查看全文
laravel-mongodb