一、什么是yii2-queue?
Yii2-queue是Yii2.0 PHP框架下一个消息队列拓展插件,支持基于DB, Redis, RabbitMQ, AMQP, Beanstalk 和 Gearman等。yii2-queue GitHub地址:https://github.com/yiisoft/yii2-queue
二、如何安装yii2-queue?
1.安装
php composer.phar require --prefer-dist yiisoft/yii2-queue
2.配置
找到你的项目配置文件,高级版是main.php,普通版console.php,在里面加上你的配置,这个yii2-queue可以使用各种驱动模式来做,我这里选取了redis,所以你得必须先有redis,如果没有可以用file来驱动
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
#linux
php 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
三、Linux systemd介绍
systemd是linux下的一款系统和服务管理器,为什么要使用systemd ? 在rpm包二进制方式安装的linux软件中,使用init守护进程进行服务状态的管理或者使用service命令 例如启动Mysql数据库可以是 /etc/init.d/mysql start 或者service mysql start.
使用linux init进程进行管理服务的时候有两个缺点:
1.init系统进程是串行执行的,也就是同步的 ,只有前一个进程启动完成,才会启动下一进程。
2.启动脚步复杂,init进程是只执行启动脚步,不管其他的任务
使用Systemd优点:
1.Systemd支持并行化任务,
2.同时采用socket于D-Bus总线式激活服务,按需启动守护进程(daemon)
在新版的Linux系统中都在使用sytemd 进行管理 例如(Ubuntu 16、Debian 8、CentOS 7)
四、在Linux创建systemd系统服务监听队列消息
1、在Linux下进入system目录,相关命令:cd /etc/systemd/system;
2、新增yii-queue@.service文件,相关命令:vi yii-queue@.service;
3、yii-queue@.service文件内容如下:
[Unit]
Description=Yii Queue Worker %I
After=network.target
# the following two lines only apply if your queue backend is mysql
# replace this with the service that powers your backend
After=mysql.service
Requires=mysql.service
[Service]
User=www-data
Group=www-data
ExecStart=/usr/bin/php /var/www/my_project/yii queue/listen --verbose
Restart=on-failure
[Install]
WantedBy=multi-user.target4、重载systemd配置文件使其生效,相关命令:
systemctl daemon-reload;
5、其他相关命令:
# 开启两个工作
systemctl start yii-queue@1 yii-queue@2
# 查看状态
systemctl status "yii-queue@*"
# 停止指定的
systemctl stop yii-queue@2
# 停止所有
systemctl stop "yii-queue@*"
# 开机自启
systemctl enable yii-queue@1 yii-queue@2 


0 条评论