2.8.4.2.6. Configure Redis in Laravel

Important points:

  • You can connect to Redis on the hosting server only via a Unix socket.
  • The PhpRedis PECL extension is available by default on the hosting platform. No additional clients need to be installed.
  • This instruction describes the general procedure for configuring Redis. It may not be suitable for sites where changes have been made to the functionality related to Redis.
  1. Edit the .env file located in the project's root directory:
    • Find the Redis configuration block:
      REDIS_HOST=127.0.0.1
      REDIS_PASSWORD=null
      REDIS_PORT=6379
    • Replace the lines with the following:
      REDIS_HOST=/home/example/.system/redis.sock
      REDIS_DB=0
      REDIS_CACHE_DB=1
      REDIS_PREFIX=doepref_
    • In the line containing the REDIS_HOST parameter, replace example with the name of the hosting account where the site is hosted.
    • In the REDIS_DB and REDIS_CACHE_DB settings, specify a unique identifier for the Redis database.
    • Specify the required prefix in the REDIS_PREFIX parameter.
  2. Edit the database.php file located in the config/ directory:
    • Find the Redis connection code in the file; it will start with 'redis' => [. The connection configuration should look something like this:
           'redis' => [
      
              'client' => env('REDIS_CLIENT', 'phpredis'),
      
              'options' => [
                  'cluster' => env('REDIS_CLUSTER', 'redis'),
                  'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
              ],
      
              'default' => [
                  'host'     => env('REDIS_HOST'),
                  'password' => env('REDIS_PASSWORD'),
                  'port'     => env('REDIS_PORT'),
                  'database' => env('REDIS_DB', 0),
              ],
      
              'cache' => [
                  'host'     => env('REDIS_HOST'),
                  'password' => env('REDIS_PASSWORD'),
                  'port'     => env('REDIS_PORT'),
                  'database' => env('REDIS_CACHE_DB', 1),
              ],
      
          ],
  3. Check that Redis is working. To test it, edit the web.php file located in the routes/ directory by adding the following code:
    Route::get('redis-test', function (){
    if(!Redis::get('test_time')){
    Redis::set('test_time', date(DATE_RFC822));
    }
    return "Date inserted in database: ".Redis::get('test_time');
    });

    Open your project at the link http://example.com/redis-test, replacing example.com with your domain name. Once you click the link, the time of the first request to that URL should be displayed.

Attention!

The Redis database ID must be unique across all CMS instances and for different types of caching to prevent errors caused by data conflicts between different services.
Content

    (1)