Installing Redis as Cache Server on Ubuntu

I recently installed Redis as a cache driver for my one Laravel application, but unfortunately I didn’t document it 🙁 Now I try the same for my other big application. Let’s have a look.

Currently I use database as a cache driver. Now I want to switch to Redis.

I start with installint predis/predis:

composer require predis/predis:^2.0

Then I followed the installation instructions on redis.io:

sudo apt-get install lsb-release curl gpg
curl -fsSL https://packages.redis.io/gpg | sudo gpg --dearmor -o /usr/share/keyrings/redis-archive-keyring.gpg
sudo chmod 644 /usr/share/keyrings/redis-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/redis-archive-keyring.gpg] https://packages.redis.io/deb $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/redis.list
sudo apt-get update
sudo apt-get install redis

After installing the server has to be enabeld to start by default and started:

sudo systemctl enable redis
sudo systemctl start redis

Then we have to install the php redis extension; as my php is version 8.2 I have to install:

sudo apt install php8.2-redis

To check if Redis is working correctly, I opend the redis-cli:

redis-cli
> keys *

This should respond with (empty array) first. Now I opened another ssh terminal with Laravels artisan tinker, where i use

$a = Cache::remember('abcd', 10, function() { return 'hugo'; });

This remembers the word „hugo“ for 10 seconds in the cache by the key „abcd“. So calling again

keys *

in the redis-cli within the 10 s, there you should see the key:

Check! So easy!