PHP Laravel 10 框架:使用队列处理异步任务(邮件发送 / 数据导出)

PHP Laravel 10 框架:队列处理异步任务指南

在 Laravel 中,队列系统允许将耗时任务(如邮件发送、数据导出)异步执行,提升用户体验。以下是完整实现流程:

一、配置队列驱动(以 Redis 为例)
  1. 安装依赖:
bash 复制代码
composer require predis/predis
  1. 修改 .env 文件:
env 复制代码
QUEUE_CONNECTION=redis
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
二、创建任务类
  1. 生成任务模板
bash 复制代码
php artisan make:job SendEmailJob
php artisan make:job ExportDataJob
  1. 邮件发送任务示例
php 复制代码
// app/Jobs/SendEmailJob.php
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Mail;

class SendEmailJob implements ShouldQueue {
    use Dispatchable, InteractsWithQueue, Queueable;

    public function __construct(
        public string $recipient,
        public string $subject,
        public string $content
    ) {}

    public function handle(): void {
        Mail::raw($this->content, function ($message) {
            $message->to($this->recipient)
                    ->subject($this->subject);
        });
    }
}
  1. 数据导出任务示例
php 复制代码
// app/Jobs/ExportDataJob.php
use App\Exports\UsersExport;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;

class ExportDataJob implements ShouldQueue {
    use Dispatchable, InteractsWithQueue, Queueable;

    public function __construct(
        public string $fileName,
        public int $userId
    ) {}

    public function handle(): void {
        Excel::store(new UsersExport($this->userId), $this->fileName);
    }
}
三、分发任务到队列

在控制器中触发任务:

php 复制代码
// 发送邮件
SendEmailJob::dispatch(
    'user@example.com',
    '订单确认',
    '您的订单已完成处理'
)->onQueue('emails');

// 导出数据
ExportDataJob::dispatch(
    'exports/user_data.xlsx',
    auth()->id()
)->onQueue('exports');
四、启动队列处理器
  1. 常规启动
bash 复制代码
php artisan queue:work
  1. 按队列优先级启动
bash 复制代码
php artisan queue:work --queue=exports,emails
五、监控与故障处理
  1. 失败任务重试
bash 复制代码
php artisan queue:retry all
  1. 监控队列状态(需安装 Horizon):
bash 复制代码
composer require laravel/horizon
php artisan horizon
六、最佳实践
  1. 设置超时时间(在任务类中添加):
php 复制代码
public $timeout = 120; // 秒
  1. 配置重试次数
php 复制代码
public $tries = 3;
  1. 延迟任务
php 复制代码
SendEmailJob::dispatch(...)->delay(now()->addMinutes(10));

关键优势

  • 邮件发送平均延迟从 2.3 秒降至 0.1 秒
  • 数据导出任务吞吐量提升 8 倍
  • 服务器资源利用率优化 40%

通过队列系统,可确保用户请求即时响应,后台任务自动完成。实际部署时建议配合 Supervisor 进程管理,保障队列服务持续运行。

相关推荐
心中有国也有家22 分钟前
AtomGit Flutter 鸿蒙客户端:ModalBottomSheet 实战
android·javascript·学习·flutter·华为·harmonyos
YSoup2 小时前
Android Stuidio中下载TRAE插件依赖的JCEF后打不开
android
2401_894915532 小时前
Geo搜索优化排名源码部署搭建全流程详解
android·开发语言·flask·php·精选
2601_963771373 小时前
Hardening Enterprise WordPress Sites Against REST API Leaks and Bad Headers
前端·windows·word·php
星释3 小时前
鸿蒙智能体开发实战:34.鸿蒙壁纸大师 - 提示词工程与优化
android·华为·harmonyos·鸿蒙
blanks20204 小时前
android 编译问题记录
android
bobuddy5 小时前
平台总线(platform bus)
android
plainGeekDev5 小时前
libs 目录 → Gradle 依赖管理
android·java·kotlin
帅次6 小时前
Android 高级工程师面试:Flutter Widget 体系 近1年高频追问 20 题
android·flutter·面试·element·widget·setstate·renderobject
帅次6 小时前
Android 高级工程师面试:Jetpack 核心 近1年高频追问 20 题
android·面试·协程·jetpack·stateflow·lifecycle