John Davidson

php - Laravel Session and Cache Read/Write Driver

0 comments
Message:


I would like to use different connection for reading and writing to session and cache.
I am using redis as cache and session storage.


Here are my env configs :


REDIS_HOST=192.168.1.230
REDIS_PASSWORD=null
REDIS_PORT=6379

REDIS_HOST_READ=192.168.1.13
REDIS_PASSWORD_READ=null
REDIS_PORT_READ=6380

CACHE_DRIVER=redis
SESSION_DRIVER=redis

My cache.php(config/cache.php) modifications :


'stores' => [ 
'redis' => [
'driver' => 'redis',
'connection' => 'default',
],

'redis-read' => [
'driver' => 'redis',
'connection' => 'read',
]
]

My database.php(config/database.php) modifications :


'redis' => [

'client' => 'phpredis',

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

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

'read' => [
'host' => env('REDIS_HOST_READ', '127.0.0.1'),
'password' => env('REDIS_PASSWORD_READ', null),
'port' => env('REDIS_PORT_READ', 6380),
'database' => 0,
'persistent'=> 1
],

],

I am able to read from redis read host as follows :


Cache::driver('redis-read')->get('general_data');

But I don't want to define this every time when I am reading cache/session.
Is there any other way to do this ? I mean whenever I am reading cache/session, it will use "redis-read" and whenever I am writing to cache/session, it will use "redis".



My Answer:
[
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'connection_read' => 'read',
],
],

'migrations' => [
'read' => [
'driver' => 'redis',
'connection' => 'read',
],
],

'redis' => [
'client' => 'predis',
'default' => [
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
'database' => 0,
],
'read' => [
'host' => env('REDIS_HOST_READ', '127.0.0.1'),
'password' => env('REDIS_PASSWORD_READ', null),
'port' => env('REDIS_PORT_READ', 6380),
'database' => 0,
],
],

'prefix' => 'laravel',
],

In this configuration, I have added a 'connection_read' key to the 'redis' store configuration in the cache.php file. This allows you to specify a separate connection for reading from the cache.

I have also added a 'read' configuration under the 'migrations' key, which specifies the connection to use for migrations.

Make sure to update your .env file with the appropriate values for REDIS_HOST_READ, REDIS_PASSWORD_READ, and REDIS_PORT_READ.

With these changes, you should be able to use a separate connection for reading from the cache while still using the default connection for writing.

Rate this post

5 of 5 based on 7396 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us