用途:在 Laravel 中构建可扩展的异步工作流,适用于实现队列任务、事件驱动流程或异步处理。目录结构约定为 app/Jobs(异步任务)、app/Events(通信标志)、app/Listeners(任务反应)。
主要能力与用法: 队列任务:用 php artisan make:job ProcessOrder 创建,类需实现 ShouldQueue,逻辑写在 handle() 中,构造函数只传模型 ID 而非完整 Eloquent 模型,通过 ProcessOrder::dispatch($orderId) 触发。 高级模式:任务链用 Bus::chain([new ProcessPayment($order), new SendReceipt($order)])->dispatch() 处理顺序依赖,用 ->catch(fn => ...) 处理失败;任务批量用 Bus::batch([new ImportRow(1), ...])->then(...)->catch(...)->dispatch(),可用 $this->batch()->cancel() 中止,通过 $batch->progress() 跟踪进度。 事件与监听器:用 php artisan make:event OrderPlaced 和 php artisan make:listener SendConfirmation --event=OrderPlaced 生成,监听器加 ShouldQueue 实现异步,用 Event::dispatch(new OrderPlaced($order)) 触发。
可靠性与监控:任务类实现 public function failed(Throwable $exception),用 public int $tries = 3 和 public int $backoff = 60 设置重试;运行 queue:failed-table 迁移跟踪失败任务;用 Laravel Horizon(php artisan horizon)做实时可观测性,生产环境不要用 queue:work。
限制与反模式:请求路径中不放重逻辑,超过 100ms 的任务应交给队列;任务载荷不传完整模型,只传 ID 由 Eloquent 运行时获取;避免过深的事件监听链;队列必须配置重试与 Horizon 告警。其他细节暂未提供。