yii2-queue 的使用

作者: guanguans | 来源:发表于2018-02-06 17:08 被阅读202次

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. 控制台

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

yii queue/listen

5. 添加到队列

  • 将任务添加到队列:
Yii::$app->queue->push(new frontend\components\DownloadJob([
    'url' => 'http://example.com/image.jpg',
    'file' => '/tmp/image.jpg',
]));
  • 将任务推送到队列中延时5分钟运行:
Yii::$app->queue->delay(5 * 60)->push(new frontend\components\DownloadJob([
    'url' => 'http://example.com/image.jpg',
    'file' => '/tmp/image.jpg',
]));

6. 测试

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

相关文章

  • Yii2队列拓展 yii2-queue的配置使用

    Yii2队列拓展 yii2-queue的配置使用 composer安装 php composer.phar req...

  • yii2-queue 的使用

    1. 安装 2. 配置,在 common/config/main.php 中配置 redis作为驱动 File 作...

  • yii2-queue

    安装 配置,在 common/config/main.php 中配置 redis作为驱动 File 作为驱动 新建...

  • iconfont的使用(下载使用)

    1、下载文件 2、在生命周期中引入项目 beforeCreate () { var domModule = ...

  • Gson的使用--使用注解

    Gson为了简化序列化和反序列化的过程,提供了很多注解,这些注解大致分为三类,我们一一的介绍一下。 自定义字段的名...

  • 记录使用iframe的使用

    默认记录一下----可以说 这是我第一次使用iframe 之前都没有使用过; 使用方式: 自己开发就用了这几个属...

  • with的使用

    下面例子可以具体说明with如何工作: 运行代码,输出如下

  • this的使用

    什么是this? this是一个关键字,这个关键字总是返回一个对象;简单说,就是返回属性或方法“当前”所在的对象。...

  • this的使用

    JS中this调用有几种情况 一:纯粹的函数调用 这是函数的最通常用法,属于全局性调用,因此this就代表全局对象...

  • ==的使用

    积累日常遇到的编码规范,良好的编码习惯,持续更新。。。 日常使用==用于判断的时候,习惯性将比较值写前面,变量写后...

网友评论

  • wyang_b504:请问下,为什么加了'as log'参数,记录日志时会报
    [warning][yii\log\Dispatcher::dispatch] Unable to send log via yii\debug\LogTarget: Exception 'yii\base\UnknownMethodException' with message 'Calling unknown method: yii\console\Request::getAbsoluteUrl()'
    guanguans:具体原因我也不是很清楚,你可以去官方看看,传送门:https://github.com/yiisoft/yii2-queue/issues

本文标题:yii2-queue 的使用

本文链接:https://www.haomeiwen.com/subject/bpbgzxtx.html