yii2-queue队列的使用
编辑于 2022-11-12 22:15:03 阅读 1629
安装
composer require yiisoft/yii2-queue
配置
//cat config/console.php
return [
'bootstrap' => [
'queue',
],
'components' => [
'redis' => [
'class' => 'yii\redis\Connection',
'hostname' => 'docker-redis',
'port' => 6379,
'database' => 0,
'retries' => 1,
],
// 'queue' => [
// 'class' => \yii\queue\file\Queue::class,
// ],
'queue' => [
'class' => \yii\queue\redis\Queue::class,
'redis' => 'redis', // Redis connection component or its config
'channel' => 'queue', // Queue channel key
],
],
];
创建任务
任务1
<?php
namespace app\job;
use yii\base\BaseObject;
class Download extends BaseObject implements \yii\queue\JobInterface {
public $url;
public $file;
public function execute($queue) {
file_put_contents($this->file, file_get_contents($this->url));
}
}
任务2
<?php
namespace app\job;
class SendEmail extends \yii\base\Component implements \yii\queue\JobInterface {
public $url;
public $title;
public function execute($queue) {
file_put_contents($this->url,"email") ;
}
}
将任务添加到队列,等待执行
\Yii::$app->queue->push(new Download([
'url' => 'https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png',
'file' => \Yii::getAlias("@app/runtime/down/bd.jpg"),
]));
//delay单位为秒
$rs = \Yii::$app->queue->delay(10)->push(new SendEmail([
'url' => \Yii::getAlias("@app/runtime/mail/aaa"),
'title'=>123,
]));
var_dump($rs);
执行任务
将队列里的任务执行一遍,适合做计划任务
./yii queue/run
创建一个守护进程,实时监听队列,有新任务就执行
./yii queue/listen //实时监听
./yii queue/listen 5 //每隔5s监听一次队列
其他命令
yii queue/info 查看队列状态
yii queue/clear 清空队列
yii queue/remove [id] 移除某个任务
参考
https://github.com/yiisoft/yii2-queue/blob/master/docs/guide/driver-redis.md