Laravel Database Redis


Laravel Database Redis – The Laravel Database Redis is used to referred to as a data structure server from key can contain string, hashes, list, sets and sorted sets.


Laravel Database Redis.

Let us understand how to use laravel Database Redis.

Function:-

There are some followings function available in laravel Database Redis.

  • 1. Introduction.
  • 2. Interacting With Redis.
  • 3. Pub / Sub.

1. Introduction.

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

Before using Redis, you will need to install the predis/predis package through composer.

composer require predis/predis

Configuration

The redis configuration for your application is placed in the config/database.php configuration file. Then you will see a redis array containing the Redis servers utilized by your application.

Let’s look at a simple example.

'redis' => [
    'client' => 'predis',

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

],

The default server configuration should suffice for development.Each redis sever defined in your configuration file is required to have a name, host, and port.

Configuring Clusters

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

Let’s look at a simple example.

'redis' => [

    'client' => 'predis',

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

],

By default, cluster will perform client-side sharding across your nodes, allowing you to pool nodes and create a large amount of available RAM.

Let’s look at a simple example.

'redis' => [

    'client' => 'predis',

    'options' => [
        'cluster' => 'redis',
    ],

    'clusters' => [
        // ...
    ],

],

Predis

In addtion to the default host, port, database and password
server configuration options, predis supports connection parameters that can be defined for each of your redis server.

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

PhpRedis

Utilize the PhpRedis extension, you should change the client option of your Redis configuration to PhpRedis.

'redis' => [

    'client' => 'phpredis',

    // Rest of Redis configuration...
],

In addition to the default, host, port, database and password server configuration options, PhpRedis supports the following additional connection parameters persistant, prefix, read_timeout and timeout.

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

2. Interacting With Redis.

We can interact with Redis by calling various method on the Redis facade. The redis facade supports dynamic methods, meaning you can call any Redis command on the facade and the command will be passed directly to Redis.

Let’s look at a simple example.

<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    public function showProfile($id)
    {
        $user = Redis::get('user:profile:'.$id);

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

As mentioned above, you can call any of the Redis commands on the Redis facade.

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

$values = Redis::lrange('names', 5, 10);

You can 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', ['name', 5, 10]);

Using Multiple Redis Connections

You can get a Redis instance by calling the Redis::connection method.

$redis = Redis::connection();

You can also pass the connection or cluster name to the connection method.

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

Pipelining Commands

Pipelining should be used when you need to send many commands to the server in one operation. The pipeline method accept one argument

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

3. Pub / Sub.

Laravel provides a simple 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.

Let’s look at a simple example.

<?php

namespace App\Console\Commands;

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

class RedisSubscribe extends Command
{
    protected $signature = 'redis:subscribe';

    protected $description = 'Subscribe to a Redis channel';

    public function handle()
    {
        Redis::subscribe(['test-channel'], function ($message) {
            echo $message;
        });
    }
}

Now we can publish message to the channel using the publish method.

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

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

Wildcard Subscriptions

We can subscribe to a wildcart channel by using psubscribe method which can be 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;
});

Advertisements

Add Comment

đź“– Read More