shanechrisbarker.co.uk

Speeding up Laravel with Redis

Published On: Monday 14th of January 2019 23:05:07

Redis is a key value caching system which integrates really easily with Laravel. It is quick and easy to setup and when used in the right places, can really speed up your application.

My use case for Redis was simple - I was building a Laravel based PokeDex which performed searches via a REST API - the PokeApi .

As the data returned from specific searches would very rarely change (a search for a information about Charmander for example will very rarely return different data to a previous search for Charmander ), we can confidently cache this data. When a new Pokemon game is released or an event occurs which may result in data being added to response, we can clear the cache and regather the new information.

With that in mind, in this article, I'll cover how to install Redis on Ubuntu 18.04 and how to integrate it into your Laravel application.

Installing Redis on your server / virtual machine

As mentioned above, the installation of Redis I'll be carrying out in this article will be on an Ubuntu 18.04 machine. To get started, fire up a terminal and run the following commands:

sudo apt-get install redis-server
sudo service redis-server start
This will install the Redis Server onto the machine and then fire it up.

If you now type

redis-cli
into your terminal, you should enter the command line interface. This is a powerful tool for administrating your Redis cache but we'll cover that a little later. For now, just type exit and hit enter to leave the program.

Getting Laravel ready

In order to use our Redis installation with Laravel, we'll next need to pull in the Predis library using Composer. In your terminal, head to the root of your application and run:

composer require predis/predis
This will add the predis dependency to your composer.json file and make it available for Laravel to use.

The next step may not even be required dependant on your install. A default installation probably wouldn't require any changes but if you're having problems, open up config/database.php and locate the following block of code:

'redis' => [
        'client' => 'predis',

        'default' => [
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => env('REDIS_DB', 0),
        ],

        'cache' => [
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => env('REDIS_CACHE_DB', 1),
        ],

    ],

You'll want to make sure the settings are correct. You can verify your host and port from the redis-cli. Simply fire it up and check the values on the left. For this setup, you should see:

127.0.0.1:6379>
These values should match up to the host and port array values. If they don't, go ahead and change them. It's important to note that this file is tracked in version control so if working in a team, you may need to do some configuring to ensure it works for everyone (though I'd assume you would all be on identical development machines anyway so shouldn't be an issue).

With that, Redis is available to our application and can be used.

Using Redis inside your application

Although Redis has a large range of commands and methods that can be utilized but the 2 main method that you'll use are:

Redis::set($keyName, $keyValue);
Redis::get($keyName);
Pretty obvious but Redis::set sets a key in the cache and Redis::get retrieves it.

For my Pokedex application, I used the pokemons name as the key and the json encoded api response as the value. This meant that upon a name being submitted for a search, I could use it to check the cache for for a record.

If the cache exists, we can go ahead and return this data to our user. If it doesn't exist, we can call the API and cache the response. This way, we never have to call the API twice for the same search term:

// where $searchTerm contains the value being search for
$redis          = new Redis();
$cachedResult   = $redis::get($searchTerm); // search cache for a key equal to our search term
if (empty($cachedResult)) { // no cached result
    $data = call_api($searchTerm); // query an api with the search term and store response
    $redis::set($searchTerm, json_encode($data)); // cache our result
    return $data;
}

// we had a cached result so go ahead decode and return it.
return json_decode($cachedResult);

Don't forget!

Ensure you import Redis into your class before you try and use it:

use Illuminate\Support\Facades\Redis;

Other Useful information

As you've seen, using Redis is very simple but it obviously has much more to it than just these get and set commands. The following information should also help you get started.

Expiring Keys

By default, Redis doesn't set expiry times on the keys within the cache. To set an expiry time on a key, call the Redis::expire() method:

Redis::set($keyName, $keyValue); // set our Redis key
Redis::expire($keyName, 180); // expire the key in 180 seconds
This would set our key to expire in 3 minutes.

Using the redis-cli

The redis-cli is a powerful command line tool used for carrying out operations on your Redis cache. To enter the redis-cli, open up a terminal and run:

redis-cli
This will enter the program. Some of the most common commands you're likely to need are:
View all keys in the cache
To view the keys currently stored in the cache, you can run:
keys *
Deleting all keys in the cache
Sometimes, you may want to clear all of the keys from within the cache. To achieve this, you can run:
flushall
Setting a key
You can set a key from within the cli:
set hello "world"

Again, this guide barely scratches the surface of what Redis can do. If you need to speed up your application, Redis is certainly a fine choice. In my case, I was able to cut down the time it took to perform a search from 2.45 seconds down to 1.17! Over 50% faster - Niiiiice!

You can find the official documentation for Redis here.