Separate Redis Store in Laravel
--
Redis is an open source, advanced key-value store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets, and sorted sets.
In this article, I will show how to separate the Redis configuration for cache, session and queue. Why separate? For me, its :-
- Easier in terms of application debugging
- Less data losses
- More application control in-memory storage
- Multiple connections
- Best production oriented configuration.
Laravel have out-of-the-box Redis configuration which give you freedom to assign your connection and storage for your application.
Here is the default connection configuration in database.php
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'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),
],
],
The problem is the default session setting all goes to default redis connection which is database 0. The moment when you run FLUSHDB
in the redis for DB 0, all the data will be gone.
Great about Redis is there is a way to partition data logically. The default database is 0 but you can change that to any number from 0–15 or more depend on your setting. Each database provides a distinct keyspace, independent from the others.
Lets reconfiguring to separate the Redis connection
For example, I want to separate session, queue, cache and horizon.
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'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')…