Redis

Introduction

Redis is an open source, advanced key-value store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets, and sorted sets.

Before using Redis with Laravel, we encourage you to install and use the PhpRedis PHP extension via PECL. The extension is more complex to install but may yield better performance for applications that make heavy use of Redis.

Alternatively, you can install the predis/predis package via Composer:

  1. composer require predis/predis

Configuration

The Redis configuration for your application is located in the config/database.php configuration file. Within this file, you will see a redis array containing the Redis servers utilized by your application:

  1. 'redis' => [
  2. 'client' => env('REDIS_CLIENT', 'phpredis'),
  3. 'default' => [
  4. 'host' => env('REDIS_HOST', '127.0.0.1'),
  5. 'password' => env('REDIS_PASSWORD', null),
  6. 'port' => env('REDIS_PORT', 6379),
  7. 'database' => env('REDIS_DB', 0),
  8. ],
  9. 'cache' => [
  10. 'host' => env('REDIS_HOST', '127.0.0.1'),
  11. 'password' => env('REDIS_PASSWORD', null),
  12. 'port' => env('REDIS_PORT', 6379),
  13. 'database' => env('REDIS_CACHE_DB', 1),
  14. ],
  15. ],

The default server configuration should suffice for development. However, you are free to modify this array based on your environment. Each Redis server defined in your configuration file is required to have a name, host, and port unless you define a single URL to represent the Redis connection:

  1. 'redis' => [
  2. 'client' => env('REDIS_CLIENT', 'phpredis'),
  3. 'default' => [
  4. 'url' => 'tcp://127.0.0.1:6379?database=0',
  5. ],
  6. 'cache' => [
  7. 'url' => 'tls://user:[email protected]:6380?database=1',
  8. ],
  9. ],

Configuring The Connection Scheme

By default, Redis clients will use the tcp scheme when connecting to your Reids servers; however, you may use TLS / SSL encryption by specifying a scheme configuration option in your Redis server configuration:

  1. 'redis' => [
  2. 'client' => env('REDIS_CLIENT', 'phpredis'),
  3. 'default' => [
  4. 'scheme' => 'tls',
  5. 'host' => env('REDIS_HOST', '127.0.0.1'),
  6. 'password' => env('REDIS_PASSWORD', null),
  7. 'port' => env('REDIS_PORT', 6379),
  8. 'database' => env('REDIS_DB', 0),
  9. ],
  10. ],

Configuring Clusters

If your application is utilizing a cluster of Redis servers, you should define these clusters within a clusters key of your Redis configuration:

  1. 'redis' => [
  2. 'client' => env('REDIS_CLIENT', 'phpredis'),
  3. 'clusters' => [
  4. 'default' => [
  5. [
  6. 'host' => env('REDIS_HOST', 'localhost'),
  7. 'password' => env('REDIS_PASSWORD', null),
  8. 'port' => env('REDIS_PORT', 6379),
  9. 'database' => 0,
  10. ],
  11. ],
  12. ],
  13. ],

By default, clusters will perform client-side sharding across your nodes, allowing you to pool nodes and create a large amount of available RAM. However, note that client-side sharding does not handle failover; therefore, is primarily suited for cached data that is available from another primary data store. If you would like to use native Redis clustering, you should specify this in the options key of your Redis configuration:

  1. 'redis' => [
  2. 'client' => env('REDIS_CLIENT', 'phpredis'),
  3. 'options' => [
  4. 'cluster' => env('REDIS_CLUSTER', 'redis'),
  5. ],
  6. 'clusters' => [
  7. // ...
  8. ],
  9. ],

Predis

To utilize the Predis extension, you should change the REDIS_CLIENT environment variable from phpredis to predis:

  1. 'redis' => [
  2. 'client' => env('REDIS_CLIENT', 'predis'),
  3. // Rest of Redis configuration...
  4. ],

In addition to the default host, port, database, and password server configuration options, Predis supports additional connection parameters that may be defined for each of your Redis servers. To utilize these additional configuration options, add them to your Redis server configuration in the config/database.php configuration file:

  1. 'default' => [
  2. 'host' => env('REDIS_HOST', 'localhost'),
  3. 'password' => env('REDIS_PASSWORD', null),
  4. 'port' => env('REDIS_PORT', 6379),
  5. 'database' => 0,
  6. 'read_write_timeout' => 60,
  7. ],

PhpRedis

The PhpRedis extension is configured as default at REDIS_CLIENT env and in your config/database.php:

  1. 'redis' => [
  2. 'client' => env('REDIS_CLIENT', 'phpredis'),
  3. // Rest of Redis configuration...
  4. ],

If you plan to use PhpRedis extension along with the Redis Facade alias, you should rename it to something else, like RedisManager, to avoid a collision with the Redis class. You can do that in the aliases section of your app.php config file.

  1. 'RedisManager' => Illuminate\Support\Facades\Redis::class,

In addition to the default host, port, database, and password server configuration options, PhpRedis supports the following additional connection parameters: persistent, prefix, read_timeout, timeout, and context. You may add any of these options to your Redis server configuration in the config/database.php configuration file:

  1. 'default' => [
  2. 'host' => env('REDIS_HOST', 'localhost'),
  3. 'password' => env('REDIS_PASSWORD', null),
  4. 'port' => env('REDIS_PORT', 6379),
  5. 'database' => 0,
  6. 'read_timeout' => 60,
  7. 'context' => [
  8. // 'auth' => ['username', 'secret'],
  9. // 'stream' => ['verify_peer' => false],
  10. ],
  11. ],

The Redis Facade

To avoid class naming collisions with the Redis PHP extension itself, you will need to delete or rename the Illuminate\Support\Facades\Redis facade alias from your app configuration file’s aliases array. Generally, you should remove this alias entirely and only reference the facade by its fully qualified class name while using the Redis PHP extension.

Interacting With Redis

You may interact with Redis by calling various methods on the Redis facade. The Redis facade supports dynamic methods, meaning you may call any Redis command on the facade and the command will be passed directly to Redis. In this example, we will call the Redis GET command by calling the get method on the Redis facade:

  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Http\Controllers\Controller;
  4. use Illuminate\Support\Facades\Redis;
  5. class UserController extends Controller
  6. {
  7. /**
  8. * Show the profile for the given user.
  9. *
  10. * @param int $id
  11. * @return Response
  12. */
  13. public function showProfile($id)
  14. {
  15. $user = Redis::get('user:profile:'.$id);
  16. return view('user.profile', ['user' => $user]);
  17. }
  18. }

As mentioned above, you may call any of the Redis commands on the Redis facade. Laravel uses magic methods to pass the commands to the Redis server, so pass the arguments the Redis command expects:

  1. Redis::set('name', 'Taylor');
  2. $values = Redis::lrange('names', 5, 10);

Alternatively, you may also pass commands to the server using the command method, which accepts the name of the command as its first argument, and an array of values as its second argument:

  1. $values = Redis::command('lrange', ['name', 5, 10]);

Using Multiple Redis Connections

You may get a Redis instance by calling the Redis::connection method:

  1. $redis = Redis::connection();

This will give you an instance of the default Redis server. You may also pass the connection or cluster name to the connection method to get a specific server or cluster as defined in your Redis configuration:

  1. $redis = Redis::connection('my-connection');

Pipelining Commands

Pipelining should be used when you need to send many commands to the server. The pipeline method accepts one argument: a Closure that receives a Redis instance. You may issue all of your commands to this Redis instance and they will all be streamed to the server thus providing better performance:

  1. Redis::pipeline(function ($pipe) {
  2. for ($i = 0; $i < 1000; $i++) {
  3. $pipe->set("key:$i", $i);
  4. }
  5. });

Pub / Sub

Laravel provides a convenient interface to the Redis publish and subscribe commands. These Redis commands allow you to listen for messages on a given “channel”. You may publish messages to the channel from another application, or even using another programming language, allowing easy communication between applications and processes.

First, let’s setup a channel listener using the subscribe method. We’ll place this method call within an Artisan command since calling the subscribe method begins a long-running process:

  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use Illuminate\Support\Facades\Redis;
  5. class RedisSubscribe extends Command
  6. {
  7. /**
  8. * The name and signature of the console command.
  9. *
  10. * @var string
  11. */
  12. protected $signature = 'redis:subscribe';
  13. /**
  14. * The console command description.
  15. *
  16. * @var string
  17. */
  18. protected $description = 'Subscribe to a Redis channel';
  19. /**
  20. * Execute the console command.
  21. *
  22. * @return mixed
  23. */
  24. public function handle()
  25. {
  26. Redis::subscribe(['test-channel'], function ($message) {
  27. echo $message;
  28. });
  29. }
  30. }

Now we may publish messages to the channel using the publish method:

  1. Route::get('publish', function () {
  2. // Route logic...
  3. Redis::publish('test-channel', json_encode(['foo' => 'bar']));
  4. });

Wildcard Subscriptions

Using the psubscribe method, you may subscribe to a wildcard channel, which may be useful for catching all messages on all channels. The $channel name will be passed as the second argument to the provided callback Closure:

  1. Redis::psubscribe(['*'], function ($message, $channel) {
  2. echo $message;
  3. });
  4. Redis::psubscribe(['users.*'], function ($message, $channel) {
  5. echo $message;
  6. });