安装
代码语言:javascript复制composer require yiisoft/yii2-queue
配置
代码语言:javascript复制//cat config/console.php
return [
'bootstrap' => [
'queue',
],
'components' => [
'redis' => [
'class' => 'yiiredisConnection',
'hostname' => 'docker-redis',
'port' => 6379,
'database' => 0,
'retries' => 1,
],
// 'queue' => [
// 'class' => yiiqueuefileQueue::class,
// ],
'queue' => [
'class' => yiiqueueredisQueue::class,
'redis' => 'redis', // Redis connection component or its config
'channel' => 'queue', // Queue channel key
],
],
];
创建任务
任务1
代码语言:javascript复制<?php
namespace appjob;
use yiibaseBaseObject;
class Download extends BaseObject implements yiiqueueJobInterface {
public $url;
public $file;
public function execute($queue) {
file_put_contents($this->file, file_get_contents($this->url));
}
}
任务2
代码语言:javascript复制<?php
namespace appjob;
class SendEmail extends yiibaseComponent implements yiiqueueJobInterface {
public $url;
public $title;
public function execute($queue) {
file_put_contents($this->url,"email") ;
}
}
将任务添加到队列,等待执行
代码语言:javascript复制 Yii::$app->queue->push(new Download([
'url' => 'https://img.yuanmabao.com/zijie/pic/2022/11/06/dgfag5yj3lj.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);
执行任务
将队列里的任务执行一遍,时候做计划任务
代码语言:javascript复制./yii queue/run
创建一个守护进程,实时监听队列,有新任务就执行
代码语言:javascript复制./yii queue/listen //实时监听
./yii queue/listen 5 //每隔5s监听一次队列
其他命令
代码语言:javascript复制yii queue/info 查看队列状态
yii queue/clear 清空队列
yii queue/remove [id] 移除某个任务
参考
https://github.com/yiisoft/yii2-queue/blob/master/docs/guide/driver-redis.md