Laravel: how to separate cache and session into different redis database?
Introduction
Here is my note, for some other guy who running in to this problem, I think this is should be in the docs.
By default, redis gives you 16 separate databases, but laravel out of the box will try to use database 0 for both sessions and cache.
Our solution is to let Redis caching using database 0, and database 1 for Session, there for solving the session clear by running php artisan cache:clear
problem.
Note: Tested at Laravel 5.1
1. Setting up Session Redis connection
Modify config/database.php
, add session
key to the redis
option:
'redis' => [ 'cluster' => false, 'default' => [ 'host' => env('REDIS_HOST', 'localhost'), 'password' => env('REDIS_PASSWORD', null), 'port' => env('REDIS_PORT', 6379), 'database' => 0, ], 'session' => [ 'host' => env('REDIS_HOST', 'localhost'), 'password' => env('REDIS_PASSWORD', null), 'port' => env('REDIS_PORT', 6379), 'database' => 1, ],],
2. Make use of the session
connection
Modify config/session.php
, change the following:
'connection' => null,
to:
'connection' => 'session',
3. Using Redis as session driver
Modify .env
, change SESSION_DRIVER
:
SESSION_DRIVER=redis
4. Testing out
Execute the following artisan command, then check your login state:
php artisan cache:clear
If the login state persists, voilĂ !
Laravel 5.5:
database.php should look like this:
'redis' => [ 'client' => 'predis', 'default' => [ 'host' => env('REDIS_HOST', '127.0.0.1'), 'password' => env('REDIS_PASSWORD', null), 'port' => env('REDIS_PORT', 6379), 'database' => 0, ], 'session' => [ 'host' => env('REDIS_HOST', '127.0.0.1'), 'password' => env('REDIS_PASSWORD', null), 'port' => env('REDIS_PORT', 6379), 'database' => 1, ],],
And in the session.php you have to update also the key "connection" to the right key. In this case 'session'
'connection' => 'session',
Laravel 5 now supports this.
https://github.com/laravel/framework/commit/d10a840514d122fa638eb5baa24c8eae4818da3e
You can select redis connection by modifying config/cache.php
'stores' => [ 'redis' => [ 'driver' => 'redis', 'connection' => 'your-connection-name', ],],
Laravel 4 CacheManager
does not support selecting redis connection.
What you need to do is to modify/extend CacheManager
and override createRedisDriver()
method.
Modify this line
return $this->repository(new RedisStore($redis, $this->getPrefix()));
To
return $this->repository( new RedisStore($redis, $this->getPrefix(), $this->app['config']['cache.redis']));
Now you can define your configuration in cache.php
'redis' => 'your-connection-name'