温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在Yii2中使用queue队列

发布时间:2021-03-24 16:27:54 来源:亿速云 阅读:497 作者:Leah 栏目:开发技术

这篇文章给大家介绍如何在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.控制台

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

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

启动worker

可以使用Supervisor或Systemd 来启动多进程worker,也可以使用 Cron,我们这里主要说一下Supervisor

centos7 supervisor的使用

1.安装supervisor

yum update
yum install epel-release
yum install -y supervisor
#开机启动
systemctl enable supervisord
#启动
systemctl start supervisord

2.supervisor 命令

supervisorctl status 查看进程状态   
supervisorctl reload 重启supervisord 
supervisorctl start|stop|restart 启动关闭重启进程

3.添加配置文件

Supervisor 配置文件通常在 /etc/supervisord.d 目录下. 你可以创建一些配置文件在这里.

注:文件名是.ini结尾

下面就是个例子:

[program:yii-queue-worker]
process_name=%(program_name)s_%(process_num)02d
command=/usr/bin/php /var/www/my_project/yii queue/listen --verbose=1 --color=0
autostart=true
autorestart=true
user=www-data
numprocs=4
redirect_stderr=true
stdout_logfile=/var/www/my_project/log/yii-queue-worker.log

关于如何在Yii2中使用queue队列就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI