Using yii2-queue and redis to implement queue function

Keywords: Programming Redis PHP Database Java

Why use it?

Activeemq has been used before, but it's Java-based. It has to be loaded with a bunch of things and configured. And I'm just a relatively simple function, so I'm not going to use it. But I'll learn later that yii2-queue can be combined.

install

First you have to install it with composer, which is very simple, under your project directory.

composer require --prefer-dist yiisoft/yii2-queue

The configuration of the bar

Find your project configuration file. The advanced version is main.php, the ordinary version is console.php. Add your configuration to it. This yii2-queue can be done with various driving modes. I chose redis here, so you have to have redis first, if not file to drive.

 // Register this component to the console
    'bootstrap' => [
        'queue',
    ],
    'components' => [
        'queue'  => [
            'class'   => \yii\queue\redis\Queue::class,
             // Connecting a component or its configuration
            'redis'   => 'redis',
           // Queue channel key
            'channel' => 'queue',
            
        ],
        'redis'  => [
            'class'    => 'yii\redis\Connection',
            'hostname' => 'localhost',
            'port'     => 6379,
            'database' => 0,
        ]
    ]
    

Configuration is as simple as that.

Use

First of all, we have to write a team file, which carries out a team task. Here I simply write a team file.

<?php
namespace common\components;
use yii\base\BaseObject;


class Job extends BaseObject implements \yii\queue\JobInterface
{
    public $url;
    public $file;

    public function execute($queue)
    {
        file_put_contents($this->file, file_get_contents($this->url));
    }
}

The above is the file executed by the queue. This is how we use it. It is usually used in the controller.

use common\components\Job;
public function actionJob(){
   //Add tasks to queues
   Yii::$app->queue->push(new Job([
   'url' => 'http://img.netpc.com.cn/2018/06/12080502tmd.jpg',
   'file' => '/Users/gongchuandong/www/project/ideaboat\1.jpg',
   ]));
  
}

// Delay 5s trigger
Yii::$app->queue->delay(5)->push(new Job([
   'url' => 'http://img.netpc.com.cn/2018/06/12080502tmd.jpg',
   'file' => '/Users/gongchuandong/www/project/ideaboat\1.jpg',
   ]));

Finally, you have to listen to this queue on the command line.

./yii queue/listen

That's all right.

pit

When I executed sql in the queue, I found a pit that I couldn't save anyway, to protect the error.

SQLSTATE[HY000] [2002] No such file or directory in

Finally, Google needs to change the database connection from localhost to 127.0.0.1, OK

Posted by Darkmatter5 on Mon, 01 Apr 2019 10:09:28 -0700