Laravel 队列指南
Laravel 异步任务处理:任务类、派发模式、失败任务处理、批处理和队列 worker 配置。
1. 创建任务
class ProcessArticleImages implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public int $tries = 3;
public int $timeout = 120;
public function __construct(private readonly Article $article) {}
public function handle(ImageProcessor $processor): void
{
foreach ($this->article->getRawImages() as $image) {
$processor->resize($image, 1200);
}
$this->article->update(['images_processed' => true]);
}
public function failed(\Throwable $e): void
{
\Log::error("图片处理失败,文章 {$this->article->id}", ['error' => $e->getMessage()]);
}
}
2. 派发任务
// 立即派发
ProcessArticleImages::dispatch($article);
// 延迟派发
ProcessArticleImages::dispatch($article)->delay(now()->addMinutes(10));
// 指定队列
ProcessArticleImages::dispatch($article)->onQueue('media');
// 数据库提交后派发(避免竞态条件)
ProcessArticleImages::dispatch($article)->afterCommit();
// 链式任务
ProcessArticleImages::dispatch($article)->chain([
new GenerateThumbnails($article),
new NotifySubscribers($article),
]);
3. Worker 命令
# 启动 worker
php artisan queue:work redis --queue=media,default --tries=3
# 处理单个任务后退出
php artisan queue:work --once
# 失败任务管理
php artisan queue:failed
php artisan queue:retry all
php artisan queue:flush
4. 队列驱动对比
| 驱动 | 适用场景 | 优势 |
|---|---|---|
| sync | 测试/简单场景 | 无需配置 |
| database | 小型应用 | 内置,无额外基础设施 |
| redis | 生产环境 | 快速,支持 Horizon |
| sqs | AWS 环境 | 完全托管 |