少廢話主要看文檔
官方文檔
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 updateyum install epel-releaseyum 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)02dcommand=/usr/bin/php /var/www/my_project/yii queue/listen --verbose=1 --color=0autostart=trueautorestart=trueuser=www-datanumprocs=4redirect_stderr=truestdout_logfile=/var/www/my_project/log/yii-queue-worker.log
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。
新聞熱點
疑難解答
圖片精選