How To Use Redis For Queuing In Laravel 5

Server Norckon 322℃ 0评论

laravel1-1

What is Redis?

Redis is an in-memory but persistent on disk database, that represents a different trade-off where very high write and read speed is achieved with the limitation of data sets that can’t be larger than the memory. Once larger than memory, it starts trading the data from the backend SQL databases by pushing and pulling the data. This, in some scenarios, can bring out great speed to the overall system.

For example, a number of people are liking or commenting on a post. While concurrent requests reach the server, it’s impossible to process all of them simultaneously at high speed because accessing the database requires a little section of the overall process time.

We tackle this by pushing the customer’s “like” request in a queue and show him the updated page while database is not updated. After sometime when the jobs in the queues start firing, his job will then be fulfilled and database will be updated at the back-end servers.

This doesn’t explain the whole queuing structure, but the example was just to give an idea of how Redis can be used.

How To Setup Redis

Make sure you have Redis installed at your local server. You can check it by following the steps below, but if you are working on Cloudways, you can skip this step and follow the next one.

wget http://download.redis.io/redis-stable.tat.gz
tar xvzf redis-stable.tat.gz
cd redis-stable
make

Now to check whether your Redis server is working or not.

$redis-clifol

Screenshotfrom2016-01-01124351

or if you are connected you will get this:

Screenshotfrom2016-01-01124435

This shows the Redis is working fine.

Changes Required to Your Project

Make sure composer.json that is in your root directory has mentioned the package required for Redis.

"require": {

         ''',

         ''',

         ''',

         "predis/predis":"~1.0",

         ''',

         '''

         },

While deploying your code on git and pulling it on your server, make sure you deploy the empty project first and run composer install/update before deploying your code.

Some conflicts were found while running the composer update with codes that are already using dependencies found in composer.

How to Make Changes to Your Project

nano the (dot)env file that is in the root directory of your project and change these settings:

CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_DRIVER=redis

nano the queue.php file in the directory /config.. and make following changes

'default' => env('QUEUE_DRIVER', 'redis'),

nano the session.php file

'driver' => env('SESSION_DRIVER', 'redis'),

Some changes will occur on your code where you are calling the Redis class. So every time you get connection to Redis class you have to declare the location, and here it is:

use Illuminate\Support\Facades\Redis;

You can use functions to make Queues for example in routes.php I configured my code like this:

Route::get('/que',function (){                                                     // route from /que
   $queue = Queue::push('LogMessage', array('message' => 'Time: '.time()));               // this will push job in queue
                               // OR
   //$queue = Queue::later($delay,'LogMessage', array('message' => 'Time: '.time()));     // this will push job in queue after $delay 
   //sleep(5);    //you can add delay here too
   
   print_r(" ".$queue." ".time());            //prints queue_id and time stamp
});


class LogMessage{                                                                //bad practice to deploy code here :p


      public function fire($job,$data){                                         //takes data and performs action.
           
           File::append(app_path().'/queue.txt',$data['message'].PHP_EOL);
           $job->delete();


       }
}

Now Let’s See If Our Queue Is Working

Make sure your application is pushing the jobs in the queue, you can take examples from the above codes.

Open Up two terminals, In one of them run:

$redis-cli
127.0.0.1:6379>lrange queues:default 0 -1

You will get the number of jobs present in the queue

Screenshotfrom2016-01-01130919-768x50

Now on the other terminal

$php artisan queue:work

You will get this as an output

Screenshotfrom2016-01-01131103

Now run lrange command again

Screenshotfrom2016-01-01131442-768x39

Here you go! You’re done setting up your Redis queue successfully on Laravel 5.2. One can see the jobs moving up the queue as you call up the worker.

By Default

Laravel offers “SYNC” queuing driver by default. It needs no installation, no changes in your code but if you are switching back from the above configurations make sure you make following changes.

nano the (dot)env file that is in the root directory of your project and change these settings:

CACHE_DRIVER=sync
SESSION_DRIVER=sync
QUEUE_DRIVER=sync

nano the queue.php file in the directory /config.. and make following changes

'default' => env('QUEUE_DRIVER', 'sync'),

Note that if you run the lrange command in your redis command line interface you won’t be seeing any more jobs entering the queue (As sync driver will be handling all of them)

To generate database queue drivers you have to look up for the documentation of Laravel click here.

REFERENCED FROM

https://www.cloudways.com/blog/redis-for-queuing-in-laravel-5/

喜欢 (1)
COMMENT
Cancel Comment

EMOJI

Hi, We need some information

  • Nickname (*)
  • E-Mail (*)
  • Website
2 Comments
  1. 受教了!呵呵!
    增达网2017-05-14 16:31 Reply
  2. 向大佬学习! xiang da lao xue xi !
    CRoot2017-01-17 19:30 Reply