在 Linux 下使用 Laravel 队列,一般流程如下(以最常用的 Redis 队列 为例):
sudo apt update
sudo apt install redis-server
启动 Redis:
sudo systemctl start redis
sudo systemctl enable redis
composer create-project laravel/laravel demo
cd demo
.envQUEUE_CONNECTION=redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
php artisan make:job SendEmail
编辑 app/Jobs/SendEmail.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;
class SendEmail implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function handle()
{
// 队列逻辑
logger('队列任务执行了');
}
}
use App\Jobs\SendEmail;
SendEmail::dispatch();
或在 Controller 中:
SendEmail::dispatch()->delay(now()->addMinutes(5));
php artisan queue:work
php artisan queue:work --daemon &
安装:
sudo apt install supervisor
创建配置:
sudo vim /etc/supervisor/conf.d/laravel-worker.conf
内容:
[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/demo/artisan queue:work --sleep=3 --tries=3
autostart=true
autorestart=true
user=www-data
numprocs=2
redirect_stderr=true
stdout_logfile=/var/www/demo/storage/logs/worker.log
更新并启动:
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start laravel-worker:*
# 查看失败任务
php artisan queue:failed
# 重试失败任务
php artisan queue:retry all
# 清空队列
php artisan queue:clear
# 监听队列(自动重启)
php artisan queue:listen
✅ 队列不执行
QUEUE_CONNECTIONstorage/logs/laravel.log✅ Linux 权限问题
chown -R www-data:www-data storage bootstrap/cache
如果你用的是 数据库队列 / RabbitMQ / 定时任务结合队列,也可以告诉我,我可以给你对应方案。