少廢話主要看文檔
官方文檔 https://github.com/yiisoft/yi...php
composer require --prefer-dist yiisoft/yii2-queue
redis做爲驅動git
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 做爲驅動github
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', ], ], ];
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)); } }
控制檯用於監聽和處理隊列任務。
cmd 下 監聽隊列redis
yii queue/listen
將任務添加到隊列:bootstrap
Yii::$app->queue->push(new frontend\components\DownloadJob([ 'url' => 'http://example.com/image.jpg', 'file' => '/tmp/image.jpg', ]));
將任務推送到隊列中延時5分鐘運行:centos
Yii::$app->queue->delay(5 * 60)->push(new frontend\components\DownloadJob([ 'url' => 'http://example.com/image.jpg', 'file' => '/tmp/image.jpg', ]));
執行 5 中的程序,控制檯監聽到,便會後臺自動 下載http://example.com/image.jpg...yii2
可使用Supervisor或Systemd 來啓動多進程worker,也可使用 Cron,咱們這裏主要說一下Supervisorapp
yum update yum install epel-release yum install -y supervisor #開機啓動 systemctl enable supervisord #啓動 systemctl start supervisord
supervisorctl status 查看進程狀態 supervisorctl reload 重啓supervisord supervisorctl start|stop|restart 啓動關閉重啓進程
Supervisor 配置文件一般在 /etc/supervisord.d 目錄下. 你能夠建立一些配置文件在這裏.
注:文件名是.ini結尾composer
下面就是個例子:frontend
[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