X
    Categories: Learn Laravel Tutorials, Tips And Guides

How to Use Redis for Queuing in Laravel 5

Reading Time: 4 minutes

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.

One way developers tackle this is by pushing the requests in a queue and display the updated page even while database is not updated. After a predefined interval, the jobs in the queues start firing and the database is updated.

Although, this doesn’t explain the entire queuing structure, this example is a great way of understanding how to use Redis.

Related: Learn How to Use Laravel Horizon for Redis Queue

Prerequisites

For the purpose of this tutorial, I assume that you have a Laravel application installed on a web server. My setup is:

  • Laravel 5.5
  • PHP 7.1
  • MySQL

I have installed a Laravel app on a Cloudways managed server because it has everything I’ll need for this tutorial and I don’t have to deal with server setup issues. If you do not have an account on Cloudways, sign up for free, and check out the following GIF to setup the server and application in just a few clicks.

 

Setup and Install Redis in Laravel

Cloudways has simplified Redis installation and the process is over is just a few clicks. To begin, go to the Server Management tab and click Setting & Packages. Go to the Packages tab and click the install button located in front of the Redis entry. Once the process finishes, the screen will look like:

Testing Load Speed and Memory Usage

The best option for testing the load speed, memory usage and the number of queries is Laravel Debugbar, simply because it has all the features I need for running the tests. To begin:

First, let’s pull the package via the following Composer command:

composer require barryvdh/laravel-debugbar

Installing Predis

Before using Redis with Laravel, I will install the Predis package through the following Composer command:

composer require predis/predis

Changes Required in the Project

Make sure that composer.json (located in the root directory) includes mentions of the package required for Redis.

"require": {

       ''',

        ''',
        ''',
        "predis/predis":"~1.0",
        ''',
        '''
        },


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

To make the changes, open the .env file (located in the root directory of the project) and change these settings:

CACHE_DRIVER=redis

SESSION_DRIVER=redis

QUEUE_DRIVER=redis

Next, open the queue.php file in the directory /config, and make the following changes.

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

Next, in the session.php file:

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

You also need to make several changes to your code where you call the Redis class. So at every call, you have to declare the location as follows:

  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('/', function () {

$queue = Queue::push('LogMessage',array('message'=>'Time: '.time()));

   return $queue;

});



class LogMessage{

public function fire($job, $date){

File::append(app_path().'/queue.txt',$date['message'].PHP_EOL);

$job->delete();

}

}

Now Let’s See If Our Queue Is Working:

Once you have pasted the code in the route/web file, run the php artisan command and check the application output by refreshing the page. If everything is working fine, it generates a random number.You will get the number of jobs present in the queue.

Redis Performance Benchmark

I will now run a Redis-benchmark script. The command will  have 1000 requests, over 10 parallel connections and the pipeline of 5 requests.

redis-benchmark -q -n 1000 -c 10 -P 5

The results will look like this:

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.

Noor Ali :Noor Ali is an Associate Software Engineer at Cloudways. He loves to solve technical problems through programming and mathematics.