Yii2.0 queue

https://www.yiichina.com/tutorial/1635

https://my.oschina.net/gcdong/blog/3031113

https://www.yii-china.com/extend/detail/4

yii2-queue

安装
首先得安装,用的是composer,这个很简单,在你的项目目录下面
composer require --prefer-dist yiisoft/yii2-queue

##配置

找到你的项目配置文件,高级版是main.php,普通版console.php,在里面加上你的配置,这个yii2-queue可以使用各种驱动模式来做,我这里选取了redis,所以你得必须先有redis,如果没有可以用file来驱动

// 把这个组件注册到控制台

 1 'bootstrap' => [
 2   'queue',
 3 ],
 4 'components' => [
 5   'queue' => [
 6     'class' => yiiqueue
edisQueue::class,
 7     // 连接组件或它的配置
 8     'redis' => 'redis',
 9     // Queue channel key
10     'channel' => 'queue', 
11   ],
12   'queue' => [
13     'class' => yiiqueuefileQueue::class,
14     // 连接组件或它的配置
15     'as log' => yiiqueueLogBehavior::class,
16     'path' => '@runtime/queue', 
17   ],
18   'redis' => [
19     'class' => 'yii
edisConnection',
20     'hostname' => 'localhost',
21     'port' => 6379,
22     'database' => 0,
23   ]
24 ]


使用
首先我们得写一个队里文件,里面执行一个队里的任务,我这里简单的写了一个

 1 <?php
 2 namespace commoncomponents;
 3 use yiiaseBaseObject;
 4 
 5 class Job extends BaseObject implements yiiqueueJobInterface
 6 {
 7     public $url;
 8     public $file;
 9 
10     public function execute($queue)
11     {
12         file_put_contents($this->file, file_get_contents($this->url));
13     }
14 }

上面是队列执行的文件,我们要使用它是这样使用的,一般在控制器里面使用

 1 use commoncomponentsJob;
 2 public function actionJob(){
 3     //添加任务到队列
 4     Yii::$app->queue->push(new Job([
 5         'url' => 'http://img.netpc.com.cn/2018/06/12080502tmd.jpg',
 6         'file' => '/www/project/ideaboat1.jpg',
 7     ]));
 8 }
 9 
10 // 延时5s触发
11 Yii::$app->queue->delay(5)->push(new Job([
12     'url' => 'http://img.netpc.com.cn/2018/06/12080502tmd.jpg',
13     'file' => '/www/project/ideaboat1.jpg',
14 ]));

最后你还得在命令行把这个队列的监听监听起来

./yii queue/listen
这样就可以了

原文地址:https://www.cnblogs.com/caohongchang/p/11164749.html