Yii2 queue的队列使用详解

 
更多

yii2-queue 队列的使用详解。

1.安装 

composer require --prefer-dist yiisoft/yii2-queue

2.配置,在 common/config/main.php 中配置 

redis作为驱动

return [
  'bootstrap' =  [
    'queue', // 把这个组件注册到控制台
  ],
  'components' =  [
    'redis' =  [
      'class' =  \yii\redis\Connection::class,
      // ...
    ],
    'queue' =  [
      'class' =  \yii\queue\redis\Queue::class,
      'as log' =  \yii\queue\LogBehavior::class,//错误日志 默认为 console/runtime/logs/app.log
      'redis' =  'redis', // 连接组件或它的配置
      'channel' =  'queue', // Queue channel key
    ],
  ],
];

File 作为驱动

return [
  'bootstrap' =  [
    'queue', // 把这个组件注册到控制台
  ],
  'components' =  [
    'queue' =  [
      'class' =  \yii\queue\file\Queue::class,
      'as log' =  \yii\queue\LogBehavior::class,//错误日志 默认为 console/runtime/logs/app.log
      'path' =  '@runtime/queue',
    ],
  ],
];

3.新建 frontend/components/DownloadJob 

class DownloadJob extends BaseObject implements \yii\queue\JobInterface
{
  public $url;
  public $file;
  
  public function execute($queue)
  {
    file_put_contents($this- file, file_get_contents($this->url));
  }
}

4.控制台 

控制台用于监听和处理队列任务。 

控制台下监听队列

yii queue/listen

5.添加到队列 

将任务添加到队列:

Yii::$app- queue- push(new frontend\components\DownloadJob([
  'url' =  'https://www.phpernote.com/image.jpg',
  'file' =  '/tmp/image.jpg',
]));

将任务推送到队列中延时5分钟运行:

Yii::$app- queue- delay(5 * 60)- push(new frontend\components\DownloadJob([
  'url' =  'https://www.phpernote.com/image.jpg',
  'file' =  '/tmp/image.jpg',
]));

6.测试 

执行 5 中的程序,控制台监听到,便会后台自动 下载https://www.phpernote.com/image.jpg到本地为/tmp/image.jpg

打赏

本文固定链接: https://www.cxy163.net/archives/2963 | 绝缘体

该日志由 绝缘体.. 于 2024年05月25日 发表在 未分类 分类下, 你可以发表评论,并在保留原文地址及作者的情况下引用到你的网站或博客。
原创文章转载请注明: Yii2 queue的队列使用详解 | 绝缘体
关键字: , , , ,

Yii2 queue的队列使用详解:等您坐沙发呢!

发表评论


快捷键:Ctrl+Enter