Laravel5.5 队列使用
今天就对 Laravel 的队列功能做个简单的事例,我使用的驱动是 redis,详细可以查看文档。
生成任务类php artisan make:queue SendMsg
就会在 app/Jobs 目录下面生成 SendMsg.php 文件,下面我们去编辑。
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Log;
class SetTopicRecommend implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
private $msg;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($msg)
{
$this->msg = $msg;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
Log::info($this->msg); // 写日志,可以在日志文件中进行查看
}
}
分发任务
分发任务有 3 中方式,具体如下:
// 在控制器中,可以直接用
$this->dispatch(new SendMsg("job test msg"));
// 类方法执行
SendMsg::dispatch("job test msg");
// 辅助函数调用
dispatch(new SendMsg("job test msg"));
// 延迟分发
SendMsg::dispatch("job test msg")->delay(now()->addMinutes(10)); // 延迟 10 分钟
执行任务
我们需要单独启用 php 来执行其任务队列,直接使用:
php artisan queue:work
后面常用参数
--queue: 执行的队列名称
--tries:任务任务失败尝试次数
--timeout:任务执行最大秒数
--daemon:后台运行,作为守护进程
--sleep: 没有任务休眠,默认为 3s
Supervisor
如果队列作为守护进程的话,需要监控,这里采用 python 写的 Supervisor,下面就是其具体配置:
/etc/supervisor/conf.d/laravel.conf
[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /home/forge/app.com/artisan queue:work sqs --sleep=3 --tries=3
autostart=true
autorestart=true
user=forge
numprocs=8
redirect_stderr=true
stdout_logfile=/home/logs/laravel.log
执行命令 supervisorctl start al
l 启动,可以用 supervisorctl status
查看状态,其他命令:
supervisorctl start
supervisorctl stop
supervisorctl status
supervisorctl restart
添加新评论