Redis

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

Before using Redis with Laravel, you will either need to install the package via Composer:

Alternatively, you may install the PHP extension via PECL. The extension is more complex to install but may yield better performance for applications that make heavy use of Redis.

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' => 'predis',
  3. 'cluster' => false,
  4. 'default' => [
  5. 'host' => env('REDIS_HOST', 'localhost'),
  6. 'password' => env('REDIS_PASSWORD', null),
  7. 'port' => env('REDIS_PORT', 6379),
  8. 'database' => 0,
  9. ],
  10. ],

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.

The cluster option will instruct the Laravel Redis client to perform client-side sharding across your Redis 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.

  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. ],

To utilize the PhpRedis extension, you should change the client option of your Redis configuration to phpredis. This option is found in your config/database.php configuration file:

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

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

You may interact with Redis by calling various methods on the Redis facade. The Redis facade supports dynamic methods, meaning you may call any 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 Illuminate\Support\Facades\Redis;
  4. use App\Http\Controllers\Controller;
  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. }

Of course, 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 simply 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

This will give you an instance of the default Redis server. If you are not using server clustering, you may pass the server name to the connection method to get a specific server as defined in your Redis configuration:

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

Pipelining should be used when you need to send many commands to the server in one operation. 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 executed within a single operation:

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

Laravel provides a convenient interface to the Redis publish and 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 since calling the subscribe method begins a long-running process:

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

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

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) {