温馨提示×

linux laravel怎样用队列

小樊
38
2026-10-01 07:24:11
栏目: 智能运维

在 Linux 下使用 Laravel 队列,一般流程如下(以最常用的 Redis 队列 为例):


一、环境准备

1. 安装 Redis(Linux)

sudo apt update
sudo apt install redis-server

启动 Redis:

sudo systemctl start redis
sudo systemctl enable redis

二、Laravel 队列配置

2. 安装 Laravel(若已有可跳过)

composer create-project laravel/laravel demo
cd demo

3. 配置 .env

QUEUE_CONNECTION=redis

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

三、创建队列任务

4. 创建 Job

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('队列任务执行了');
    }
}

四、分发队列任务

5. 调用队列

use App\Jobs\SendEmail;

SendEmail::dispatch();

或在 Controller 中:

SendEmail::dispatch()->delay(now()->addMinutes(5));

五、启动队列消费者(Linux 关键)

6. 前台运行(测试)

php artisan queue:work

7. 后台运行(推荐)

php artisan queue:work --daemon &

8. 使用 Supervisor(生产环境推荐)

安装:

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

七、常见问题

✅ 队列不执行

  • 检查 Redis 是否启动
  • 检查 QUEUE_CONNECTION
  • 查看 storage/logs/laravel.log

✅ Linux 权限问题

chown -R www-data:www-data storage bootstrap/cache

如果你用的是 数据库队列 / RabbitMQ / 定时任务结合队列,也可以告诉我,我可以给你对应方案。

0 踩