2.8.4.2.6. Setting up Redis in Laravel

Important points:

  • Connect to Redis on a hosting it is possible only through Unix-socket.
  • PECL extension is available by default on hosting PhpRedis... There is no need to install additional clients.
  • The instructions describe a general way to configure Redis. It may not be suitable for sites where changes have been made to the functionality of working with Redis.
  1. Edit the file .envlocated in the root of the project:
    • Find the Redis config 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 with the parameter REDIS_HOST insteadof example indicate hosting account namein which the site is hosted.
    • In parameters REDIS_DB and REDIS_CACHE_DB provide a unique identifier for the Redis database.
    • In the parameter REDIS_PREFIX specify the required prefix.
  2. Edit the file database.phplocated in the directory config/:
    • Find the code for connecting to Redis in the file, it will start with 'redis' => [... The connection setup 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 Redis is working. For the test, edit the file web.phplocated in the directory routes/by adding the following code to it:
    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 by link http://example.com/redis-testwhere instead of example.com enter your domain name. After the transition, the time of the first access to this link should be displayed.

Attention!

The Redis database ID must be unique for all CMS and for different types of caching so that there are no errors with the intersection of data from different services.
Content