Laravel 的队列系统是处理异步任务的核心组件,合理优化可以显著提升应用性能。以下是一些关键的优化策略:
sync
或 database
配置示例 (.env
):
QUEUE_CONNECTION=redis
php artisan queue:work --queue=high,default --timeout=60 --tries=3 --sleep=3 --memory=128
--queue
: 设置优先级队列--timeout
: 适当设置超时时间--tries
: 失败重试次数--sleep
: 无任务时休眠时间--memory
: 内存限制Supervisor 配置示例 (/etc/supervisor/conf.d/laravel-worker.conf
):
[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /path/to/artisan queue:work --sleep=3 --tries=3
autostart=true
autorestart=true
user=forge
numprocs=8
redirect_stderr=true
stdout_logfile=/path/to/storage/logs/worker.log
ShouldQueue
接口class ProcessPodcast implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $tries = 3;
public $maxExceptions = 3;
public $timeout = 120;
public $backoff = [60, 120, 300];
public function handle()
{
// 任务处理逻辑
}
}
$batch = Bus::batch([
new ProcessPodcast($podcast1),
new ProcessPodcast($podcast2),
new ProcessPodcast($podcast3),
])->then(function (Batch $batch) {
// 所有任务成功完成
})->catch(function (Batch $batch, Throwable $e) {
// 首个失败任务
})->finally(function (Batch $batch) {
// 批处理完成
})->dispatch();
'redis' => [
'queue' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_QUEUE_DB', '1'),
'read_timeout' => 60,
],
],
Redis::pipeline(function ($pipe) {
for ($i = 0; $i < 1000; $i++) {
$pipe->set("key:$i", $i);
}
});
composer require laravel/horizon
php artisan horizon:install
Queue::looping(function () {
if (memory_get_usage() > 64 * 1024 * 1024) {
exit(1); // 重启工作进程
}
});
delay()
方法unique()
方法避免重复任务// 优先级队列示例
ProcessPodcast::dispatch($podcast)->onQueue('high');
// 延迟任务
ProcessPodcast::dispatch($podcast)->delay(now()->addMinutes(10));
// 唯一任务
ProcessPodcast::dispatch($podcast)->uniqueId($podcast->id);
通过以上优化策略,可以显著提升 Laravel 队列系统的性能和可靠性。根据实际应用场景选择合适的组合方案,并持续监控队列性能指标进行调整。