Laravel Redis

Laravel Redis

Laravel 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.

Composer require predis/predis

Configuration

The Redis configuration for your application is located in the config/database.php.

Predis

'default' => [
    'host' => env('REDIS_HOST', 'localhost'),
    'password' => env('REDIS_PASSWORD', null),
    'port' => env('REDIS_PORT', 6379),
    'database' => 0,
    'read_write_timeout' => 60,
],

supports additional connection parameters that may be defined for each of your Redis servers.

PhpRedis

'redis' => [

    'client' => 'phpredis',

    // Rest of Redis configuration...
],
'default' => [
    'host' => env('REDIS_HOST', 'localhost'),
    'password' => env('REDIS_PASSWORD', null),
    'port' => env('REDIS_PORT', 6379),
    'database' => 0,
    'read_timeout' => 60,
],

supports the following additional connection parameters: persistent, prefix, read_timeout and timeout.

Interacting With Redis

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redis;

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]);
    }
}
Redis::set('name', 'Taylor');

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

Pub / Sub

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.

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

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;
        });
    }
}
Route::get('publish', function () {
    // Route logic...

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

Laravel Redis — Structure map

Clickable & Draggable!

Laravel Redis — Related pages: