Redis

Introducción

Redis es un sistema avanzado de almacenamiento llave-valor de código abierto. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets, and sorted sets. Antes de utilizar la caché Redis con Laravel, necesitarás instalar el paquete predis/predis (~ 1.0) a través de Composer.

Configuración

The Redis configuration for your application is located in the config/database.php configuration file. Dentro de este archivo, encontrarás un array redis que contiene los servidores Redis utilizados por tu aplicación:

'redis' => [

    'cluster' => false,

    'default' => [
        'host'     => '127.0.0.1',
        'port'     => 6379,
        'database' => 0,
    ],

],

La configuración por defecto del servidor debe ser suficiente para el desarrollo de tu aplicación. Sin embargo, eres libres de modificar el array basado en tu entorno. Simplemente debes darle a cada servidor Redis un nombre, y especificar el host y el puerto utilizado por el servidor.

La opción cluster le dirá al cliente Redis de Laravel que deberá realizar sharding del lado del cliente a través de tus nodos Redis, permitiéndote realizar pool de nodos y crear una gran cantidad de memoria RAM disponible. Sin embargo, ten en cuenta que el sharding del lado del cliente no soporta tolerancia de fallos; por lo tanto, sirve principalmente para datos cacheados que están disponibles en otro almacén de datos primario.

If your Redis server requires authentication, you may supply a password by adding a password configuration item to your Redis server configuration array.

Nota: Si tienes la extensión PHP de Redis instalada mediante PECL, tendrás que cambiar el nombre del alias de Redis en el archivo config/app.php.

Uso básico

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 GET command on Redis by calling the get method on the Redis facade:

<?php

namespace App\Http\Controllers;

use Redis;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * Show the profile for the given user.
     *
     * @param  int  $id
     * @return Response
     */
    public function showProfile($id)
    {
        $user = Redis::get('user:profile:'.$id);

        return view('user.profile', ['user' => $user]);
    }
}

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:

Redis::set('name', 'Taylor');

$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:

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

Using Multiple Redis Connections

Es posible obtener una instancia Redis llamando al método Redis::connection :

$redis = Redis::connection();

Esto te entregará una instancia del servidor Redis predeterminado. Si no estás utilizando clústeres de servidor, puedes pasar el nombre del servidor al método connection para obtener un servidor en específico definido en tu configuración Redis:

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

Pipelining Commands

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:

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

Pub / Sub

Laravel also 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 / processes.

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

<?php

namespace App\Console\Commands;

use Redis;
use Illuminate\Console\Command;

class RedisSubscribe extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'redis:subscribe';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Subscribe to a Redis channel';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        Redis::subscribe(['test-channel'], function($message) {
            echo $message;
        });
    }
}

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

Route::get('publish', function () {
    // Route logic...

    Redis::publish('test-channel', json_encode(['foo' => 'bar']));
});

Wildcard Subscriptions

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

Redis::psubscribe(['*'], function($message, $channel) {
    echo $message;
});

Redis::psubscribe(['users.*'], function($message, $channel) {
    echo $message;
});