Less bullshit, mainly documents
Official documents https://github.com/yiisoft/yi...
Use of yii2 queue
1. installation
composer require --prefer-dist yiisoft/yii2-queue
2. Configure in common/config/main.php
redis as driver
return [ 'bootstrap' => [ 'queue', // Register this component to the console ], 'components' => [ 'redis' => [ 'class' => \yii\redis\Connection::class, // ... ], 'queue' => [ 'class' => \yii\queue\redis\Queue::class, 'as log' => \yii\queue\LogBehavior::class,//The default error log is console/runtime/logs/app.log 'redis' => 'redis', // Connection component or its configuration 'channel' => 'queue', // Queue channel key ], ], ];
File as driver
return [ 'bootstrap' => [ 'queue', // Register this component to the console ], 'components' => [ 'queue' => [ 'class' => \yii\queue\file\Queue::class, 'as log' => \yii\queue\LogBehavior::class,//The default error log is console/runtime/logs/app.log 'path' => '@runtime/queue', ], ], ];
3. Create a 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. console
The console is used to listen and process queue tasks.
Listening queue under cmd
yii queue/listen
5. Add to queue
To add a task to a queue:
Yii::$app->queue->push(new frontend\components\DownloadJob([ 'url' => 'http://example.com/image.jpg', 'file' => '/tmp/image.jpg', ]));
Push the task to the queue, delaying 5 minutes to run:
Yii::$app->queue->delay(5 * 60)->push(new frontend\components\DownloadJob([ 'url' => 'http://example.com/image.jpg', 'file' => '/tmp/image.jpg', ]));
6. test
Execute the program in 5. If the console listens, it will download automatically in the background. http://example.com/image.jpg...
Start worker
You can use supervisor or Systemd to start multi process worker, or Cron. Let's talk about Supervisor here.
The use of centos7 supervisor
1. Install supervisor
yum update yum install epel-release yum install -y supervisor #Boot up systemctl enable supervisord #start-up systemctl start supervisord
2.supervisor command
Supervisor CTL status view process status Supervisor CTL reload restart Supervisor supervisorctl start|stop|restart start and close the restart process
3. Add profile
The supervisor configuration file is usually in the / etc / Supervisor. D directory. You can create some configuration files here.
Note: the filename ends with. ini
Here is an example:
[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