少廢話主要看文檔
yii2-queue 的使用
1.安裝
1
|
composer require --prefer-dist yiisoft/yii2-queue |
2.配置,在 common/config/main.php 中配置
redis作為驅(qū)動
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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 作為驅(qū)動
1
2
3
4
5
6
7
8
9
10
11
12
|
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
1
2
3
4
5
6
7
8
9
10
|
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.控制臺
控制臺用于監(jiān)聽和處理隊列任務。
cmd 下 監(jiān)聽隊列
1
|
yii queue/listen |
5.添加到隊列
將任務添加到隊列:
1
2
3
4
|
Yii:: $app ->queue->push( new frontend\components\DownloadJob([ 'url' => 'http://example.com/image.jpg' , 'file' => '/tmp/image.jpg' , ])); |
將任務推送到隊列中延時5分鐘運行:
1
2
3
4
|
Yii:: $app ->queue->delay(5 * 60)->push( new frontend\components\DownloadJob([ 'url' => 'http://example.com/image.jpg' , 'file' => '/tmp/image.jpg' , ])); |
6.測試
執(zhí)行 5 中的程序,控制臺監(jiān)聽到,便會后臺自動 下載http://example.com/image.jpg到本地為/tmp/image.jpg
啟動worker
可以使用Supervisor或Systemd 來啟動多進程worker,也可以使用 Cron,我們這里主要說一下Supervisor
centos7 supervisor的使用
1.安裝supervisor
1
2
3
4
5
6
7
|
yum update yum install epel-release yum install -y supervisor #開機啟動 systemctl enable supervisord #啟動 systemctl start supervisord |
2.supervisor 命令
1
2
3
|
supervisorctl status 查看進程狀態(tài) supervisorctl reload 重啟supervisord supervisorctl start|stop|restart 啟動關閉重啟進程 |
3.添加配置文件
Supervisor 配置文件通常在 /etc/supervisord.d 目錄下. 你可以創(chuàng)建一些配置文件在這里.
注:文件名是.ini結(jié)尾
下面就是個例子:
1
2
3
4
5
6
7
8
9
|
[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 |
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://segmentfault.com/a/1190000019805030