yii2 queue 的使用

柔情只为你懂 2022-05-16 15:48 374阅读 0赞

yii2 queue 的使用

1. 安装

  1. composer require --prefer-dist yiisoft/yii2-queue
  2. 复制代码

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

  • redis作为驱动

    return [

    1. 'bootstrap' => [
    2. 'queue', // 把这个组件注册到控制台
    3. ],
    4. 'components' => [
    5. 'redis' => [
    6. 'class' => \yii\redis\Connection::class,
    7. // ...
    8. ],
    9. 'queue' => [
    10. 'class' => \yii\queue\redis\Queue::class,
    11. 'as log' => \yii\queue\LogBehavior::class,//错误日志 默认为 console/runtime/logs/app.log
    12. 'redis' => 'redis', // 连接组件或它的配置
    13. 'channel' => 'queue', // Queue channel key
    14. ],
    15. ],

    ];
    复制代码

  • File 作为驱动

    return [

    1. 'bootstrap' => [
    2. 'queue', // 把这个组件注册到控制台
    3. ],
    4. 'components' => [
    5. 'queue' => [
    6. 'class' => \yii\queue\file\Queue::class,
    7. 'as log' => \yii\queue\LogBehavior::class,//错误日志 默认为 console/runtime/logs/app.log
    8. 'path' => '@runtime/queue',
    9. ],
    10. ],

    ];
    复制代码

3. 新建 frontend/components/DownloadJob

  1. class DownloadJob extends BaseObject implements \yii\queue\JobInterface
  2. {
  3. public $url;
  4. public $file;
  5. public function execute($queue)
  6. {
  7. file_put_contents($this->file, file_get_contents($this->url));
  8. }
  9. }
  10. 复制代码

4. 控制台

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

  1. yii queue/listen
  2. 复制代码

5. 添加到队列

  • 将任务添加到队列:

    Yii::$app->queue->push(new frontend\components\DownloadJob([

    1. 'url' => 'http://example.com/image.jpg',
    2. 'file' => '/tmp/image.jpg',

    ]));
    复制代码

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

    Yii::$app->queue->delay(5 * 60)->push(new frontend\components\DownloadJob([

    1. 'url' => 'http://example.com/image.jpg',
    2. 'file' => '/tmp/image.jpg',

    ]));
    复制代码

6. 测试

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

参考文献:

https://juejin.im/post/5aa770546fb9a028bd4bfbdf

发表评论

表情:
评论列表 (有 0 条评论,374人围观)

还没有评论,来说两句吧...

相关阅读