niels / Software / #laravel

Redis Sentinel with Laravel

As the use of Redis Sentinel with Laravel does not appear to be documented at the time of writing, I’m sharing the configuration I’m using.

This is the redis section of my config/database.php:

    'redis' => [

        'client' => env('REDIS_CLIENT', 'predis'),

        'options' => [

            // Don't set 'cluster' option. The only valid values are 'predis' and 'redis',
            // both conflict with sentinel replication.
            // 'cluster' => env('REDIS_CLUSTER', 'predis'),

            'prefix' => Str::slug(env('APP_NAME', 'laravel'), '_') . '_database_',
        ],

        'default' => env('REDIS_SENTINELS', false) ? array_merge(
            array_map(function ($host) {
                return "tcp://{$host}:26379?timeout=0.1";
            }, explode(',', env('REDIS_SENTINELS', ''))),
            [
                'options' => [
                    'replication' => 'sentinel',
                    'service' => 'mymaster',
                    'parameters' => [
                        'database' => 0,
                        'password' => env('REDIS_PASSWORD', null),
                    ],
                ],
            ]
        ) : [
            'url' => env('REDIS_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => 0,
        ],

        'cache' => env('REDIS_SENTINELS', false) ? array_merge(
            array_map(function ($host) {
                return "tcp://{$host}:26379?timeout=0.1";
            }, explode(',', env('REDIS_SENTINELS', ''))),
            [
                'options' => [
                    'replication' => 'sentinel',
                    'service' => 'mymaster',
                    'parameters' => [
                        'database' => 1,
                        'password' => env('REDIS_PASSWORD', null),
                    ],
                ],
            ]
        ) : [
            'url' => env('REDIS_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => 1,
        ],

    ],

And this is what I have in my .env:

REDIS_SENTINELS=10.62.0.5,10.62.0.9,10.62.0.11,10.62.0.12
REDIS_HOST=10.62.0.5
REDIS_PASSWORD=null
REDIS_PORT=6379

Summary of what it does:

  • Define REDIS_SENTINELS and it will use the Sentinel configuration.
  • Omit or set to false REDIS_SENTINELS and it will use the regular stand-alone Redis.
  • Both Sentinel and non-Sentinel Laravel instances can operate in a mixed environment due to sharing the same prefixes.
0 comments

Leave a Reply

Your email address will not be published. Required fields are marked *