Optimize Laravel with Redis, Caching Made Easy.
Untuk pembaca berbahasa Indonesia periksa link ini.
Have you ever facing a problem like this?
Although you have used a simple query like this:
So how to improve the performance or optimize it? In a Laravel development, you may need to utilize awesome features like Cache or Queue to drastically improve the performance or to defer the Process of time-consuming Jobs respectively. For configuration of Laravel Cache or Laravel Queue require you to choose a driver. Among all other available driver options, Redis is one.
Due to the flexibility of the Redis, it’s something cool that you must try, Redis gives a structured way to store data in memory. Therefore it is faster than your traditional database that writes to disk. However Redis offers a few more data structures to store your data in, it provides data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes, and streams. Due to these features, Redis is often used to store state temporarily. This is common with microservice architectures, session stores, and data that doesn’t need long-term persistence.
How Laravel-Redis Works
- Cache hit: read data from cache
- Cache miss(if cache is empty): read data from database
- Retrieve data from database
- Write data to cache, for later use.
How to Install Redis
For this case, I used Ubuntu 20.04 LTS. If you use any other Linux-based just like Fedora/CentOS, you can follow other guides to install Redis on your machine or server.
step — 1: Installing Redis
I will use the APT
package manager to install Redis from the official Ubuntu repositories. As usual start with updating the repositories by typing:
sudo apt update
After that, install Redis by typing:
sudo apt install redis-server
Once Redis installation is done, open this file with your preferred text editor, I like to use nano so that:
sudo nano /etc/redis/redis.conf
Since I am running Ubuntu, which uses the systemd init system, change this to systemd
, then it will look like this:
After we saved it. Don’t forget to restart its service, by typing:
sudo systemctl restart redis.service
Check your Redis is installed and running as well, by typing:
sudo systemctl status redis
And it will look like this if everything is correct:
step — 2: Testing Redis
I have installed Redis and it’s running. and now to test that Redis is functioning correctly, connect to the server using redis-cli
, Redis’s command-line client:
redis-cli
In the prompt that follows, we can test connectivity with the ping
command and it will show like this:
Next, check that we are able to set and get keys on Redis, here for the example:
If everything is okay, we can exit by typing theexit
command.
step — 3: Configuring Redis
By default, Redis is only accessible from localhost. In case, you might have updated the configuration file to allow connections from anywhere. But it may not as secure as binding to localhost.
To do this, open the Redis configuration file for editing:
sudo nano /etc/redis/redis.conf
Locate this line and make sure it is uncommented (remove the #
if it exists):
After you saved it, don’t forget to restart Redis service again.
To enable one of its two built-in Redis’s security features — the auth
command, which requires clients to authenticate to access you Redis’s data. We can configure the password directly in Redis’s configuration file, /etc/redis/redis.conf
, so open that file again and then find for # requirepass foobared
. Uncomment it by removing the #
, and change foobared
to a secure password.
(Optional) we also can generate an unreadable string for a secure password by using OpenSSl
and typing:
openssl rand 60 | openssl base64 -A
And you will get a random unreadable string like this:
DjjH7JR3gw4VhcumrVX0dS+VhFkV9AkbvGok+wYB2nojSFvsAWkEYQ+wsG2g4vTDJOQdQt7BPRonxjkx
Then put in after requirepass
on the security configuration of Redis.
After setting the password, save and close the file, then restart Redis:
sudo systemctl restart redis.service
Then test it using redis-cli
, if the password exists it will show like this:
To pass the authentication use auth
command with the password, for example:
And now we finished to setup Redis on the server. Next, we will configure the Laravel project for Redis.
Configuring Redis for Laravel Project
Before using a Redis cache with Laravel, there is two way to work with it. It is either install the PhpRedis
PHP extension via PECL or install the predis/predis
package (~1.0) via Composer.
step — 1: Installing Redis package for Laravel
In this case, I will use predis/predis
package. With this method, we don’t need to add a PHP extension. So that, before using Redis with Laravel, We need to install the package via Composer by typing:
composer require predis/predis
step — 2: Configure Redis for Laravel Project
The Redis configuration for your application is located in the config/database.php
configuration file. Within this file, you will see a redis
array containing the Redis servers utilized by your application:
Since I use predis package as the client, I set 'predis'
as the 'client'
. However, you want to use PhpRedis so set it as 'phpredis'
on it. Or you can set it at .env
like this:
REDIS_CLIENT=predisREDIS_HOST=127.0.0.1REDIS_PASSWORD=it-is-an-our-secretREDIS_PORT=6379
And now we can use Redis on the Laravel Project :)
How to use Redis on Laravel (In My Case)
To use Redis on a Laravel project, we can use Cache facedade
or Redis facedade
provided by Laravel. In this case, I will make my server remember the retrieved data from the database on Redis using Caching methods then I will use the Cache facedade
.
First of all, check my source code again:
Then, since I use Cache facedade by Laravel, I need to call on the top of my code:
<?phpnamespace App\Http\Controllers; use Illuminate\Support\Facades\DB;use Illuminate\Support\Facades\Cache; // <= call this!
Since I want to make Laravel remember the retrieved data, I will use Cache::remember
method:
This method has 3 parameters:
users
is the key name for the Redis,$seconds
is how long the data is stored,function(){}
is a function that returns data that will be saved on the Redis.
In my case, it will be like this:
With this code, I expect to cache the news table from my third database on my server for about 2.5 hours.
And now It is time to testing it. I will use insomnia.rest once again. then, here is the result:
Boom! As you see, now the response time is around 330ms. It is ±195% faster than before.
Summary
So, Laravel has a built-in caching feature that is supported by Redis. Redis keeps its database completely in memory, using disk only for persistence. So that the response will still be slower when the data is not in Redis yet. Besides, there is also a delay in updating data from our central database to our Redis Caching.
What do you think? Have you ever faced a similar problem? How do you solve the problem? Please share your thoughts in the comments section :) Thank you.