1.使用redis作为队列,修改config的queue配置,修改.nev QUEUE_CONNECTION = redis
2.创建执行队列的工作类,php artisan make:job TestJob, 这个时候会在 项目目录/app/Jobs目录中发现job文件
3.然后我们在这个job类的handle方法中编写对应的操作,这个handle方法是每次队列出一条任务的时候回去执行里面的步骤,如果存在异常会导致任务失败,将会进行任务的重试
我们写一条最简单的打印任务进行测试:
public function handle()
{
var_dump("队列任务测试");
}
4.新增一个控制器方法,并添加提交任务的方法
public function testJob(){
TestDumpJob::dispatch();
var_dump('testJob');
}
可以把job工作类注册到appServiceProvider,绑定到容器里面,控制反转,减少耦合。
5.启动监控队列指令
php artisan queue:work --queue=队列名称 --daemon
6.修改配置完后需要重启队列, php artisan queue:restart
7.这个队列要想变成守护进程,需要使用Supervisor
(1)yum install python-setuptools
(2)easy_install supervisor
8.安装好supervisor后,配置
/etc/supervisord.conf 在[include]下添加
files = /etc/supervisor/conf.d/*.conf
新增 /etc/supervisor/conf.d/laravel-work.conf文件,并写入
[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=/usr/local/php/bin/php /data/wwwroot/app.com/artisan queue:work redis --sleep=3 --tries=3
autostart=true
autorestart=true
user=www
numprocs=8
redirect_stderr=true
stdout_logfile=/data/wwwroot/app.com/storage/logs/queue.log
这个文件的具体数据需要根据服务器来具体配置
9.启动
supervisord -c /etc/supervisord.conf
一些命令
supervisorctl status
supervisorctl stop xxx
supervisorctl start xxx
supervisorctl restart xxx
supervisorctl reread
supervisorctl update
添加新的配置文件只需要在/etc/supervisord.d中添加配置xxx.ini文件,然后再 supervisorctl update 就可以看到了新加的进程
配置文件ini样本:
[program:crm_msg_list]
command=/usr/bin/php72 artisan queue:work --queue=msg_list --daemon
directory=/www/wwwroot/www.yiihuu.com/yiihuu-crm/
autorestart=true
startsecs=3
startretries=3
stdout_logfile=/www/server/panel/plugin/supervisor/log/crm_msg_list.out.log
stderr_logfile=/www/server/panel/plugin/supervisor/log/crm_msg_list.err.log
stdout_logfile_maxbytes=2MB
stderr_logfile_maxbytes=2MB
user=www
priority=999
numprocs=3
process_name=%(program_name)s_%(process_num)02d