Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Redis Integration with Laravel

Tags: redis

Redis is an open-source, in-memory data store that is widely used as a caching mechanism, message broker, and general-purpose database. It is known for its speed, flexibility, and support for various data structures. Redis is designed for high performance, supporting various operations with low latency due to its in-memory nature. It is often used to speed up web applications by caching frequently accessed data, managing session data, and as a message broker in distributed systems.

Redis is

  • Ultra-fast in-memory key-value data store.
  • Powerful data structure server.
  • Open-source software: Redis

Redis stores data structures:

  • Strings, lists, hashes, sets, sorted sets, etc.
  • Publish/subscribe messaging

Redis Features:

  • In-Memory Data Store: Redis stores data primarily in memory, making it exceptionally fast for read and write operations.
  • Data Structures: Redis supports a variety of data structures, including strings, lists, sets, sorted sets, and hashes. This versatility allows developers to model complex data structures easily.
  • Persistence Options: Although Redis is an in-memory database, it provides multiple options for persisting data to disk. This ensures durability and allows for data recovery in case of server restarts or failures.
  • Replication: Redis supports master-slave replication, enabling data to be asynchronously replicated across multiple nodes. This feature improves fault tolerance and scalability by distributing read operations among multiple replicas.
  • High Availability with Redis Sentinel: Redis Sentinel is a built-in monitoring and failover solution that ensures high availability by automatically detecting and recovering from failures. It monitors Redis instances and promotes replicas to masters when necessary.
  • Cluster Support: Redis Cluster allows for distributed data storage and automatic sharding across multiple Redis nodes. This feature enables horizontal scaling and provides improved performance and fault tolerance for large-scale deployments.
  • Pub/Sub Messaging: Redis supports publish/subscribe messaging, allowing clients to subscribe to channels and receive messages published to those channels in real time. This feature is useful for building real-time communication systems and message queues.
  • Lua Scripting: Redis allows users to execute Lua scripts on the server side, enabling complex operations and transactions that involve multiple Redis commands. Lua scripting enhances Redis’s flexibility and extensibility.
  • Transactions: Redis supports atomic transactions using multi/exec commands, allowing multiple commands to be executed as a single transaction. This ensures data consistency and integrity in multi-step operations.
  • Security: Redis provides authentication mechanisms to secure access to the database, allowing users to require a password for client connections. Additionally, users can configure network access controls and encryption to protect data in transit.

Install Redis:

  • To install Redis on Linux / Mac OS X:
    • Download Redis for Linux / Mac OS X
  • To download Redis on Windows:
    • Download on Windows

Redis Commands:

Redis works as an interpreter of commands:

  • Play with the command-line client
    • redis-cli 
  • Or play with Redis online at
    • Play with Redis

Integrating Redis with Laravel:

Before using Redis with Laravel.

Install the predis/predis package via Composer. Predis is a Redis client written entirely in PHP and does not require any additional extensions. You can install it via Composer.

Just run this command and you’re done.

composer require predis/predis

Apart from this, you can also install php redis, a php extension via PECL. This package is comparatively complex to install so it is better to use predis package via composer.

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:

'redis' => [

………

],

If you would like your application to interact with Redis via the Predis package, you should ensure the REDIS_CLIENT environment variable’s value is predis:

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 your application’s config/database.php configuration file:

'default' => [

            'host' => env('REDIS_HOST', 'localhost'),

            'password' => env('REDIS_PASSWORD'),

            'port' => env('REDIS_PORT', 6379),

            'database' => 0,

            'read_write_timeout' => 60,

     ]

Now configuring the Redis connection in your Laravel application. Open the .env file and update the following values:

CACHE_DRIVER=redis

REDIS_HOST=127.0.0.1

REDIS_PASSWORD=null

REDIS_PORT=6379

REDIS_CLIENT=predis

You can adjust the values according to your Redis server configuration.

Interacting with Redis:

REDIS FACADE:

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

Redis facade is used by default 0 databases, this is configured in config\database.php file.

'default' => [

        'database' => env('REDIS_DB', '0'),

     ],

In this example, we will show that get, set, and del commands will be passed directly to the Redis facade.“set” store a value in the Redis cache. “get”  retrieves a value from the Redis cache. “del”  removes the key from the Redis cache. 

You can read more about it in the: Laravel Redis documentation:

setRedis($keyName, $id);

        $user = Redis::get($keyName);

        return view('profile', compact('user'));

    }

/**

     * User set in redis

     */

    private function setRedis($keyName, $id)

    {

        if (!Redis::exists($keyName)) {

            $user = User::find($id);

            Redis::set($keyName, $user);

        }

    }

    /**

     * Remove the specified resource from storage.

     *

     * @param int $id

     * @return \Illuminate\Http\Response

     */

    public function destroy($id)

    {

        $keyName = "user:{$id}";

        Redis::del($keyName);

        return redirect('users');

    }

}

CACHE FACADE:

Laravel provides a unified caching API, and Redis can be used as the cache driver. You can access the Redis cache instance using the Cache facade or the cache() helper function.

Cache facade is used by default 1 database, this is configured in config\database.php file.

'cache' => [

        'database' => env('REDIS_DB', '1'),

     ],

In this example, we will show that “put”,  “get”, rememberForever” and “remember” methods will be passed directly to the Cache facade. “rememberForever” store a value in the Redis cache until you delete the key. “remember” store a value in the Redis cache with the time, after the time it reset. “put” store a value in the Redis cache with the time, after the time it reset. If the storage time is not passed to the put method, the item will be stored indefinitely. “get”  retrieves a value from the Redis cache. 

You can read more about it in the: Laravel Cache documentation

get('key');

        return view('profile', compact('user_forever', 'user', 'value'));

    }

    /**

     * Remove the specified resource from storage.

     *

     * @param int $id

     * @return \Illuminate\Http\Response

     */

    public function destroy($id)

    {

        $keyName = "user:{$id}";

        Cache::forget($keyName);                

        Cache::forget("forever:$keyName");    

   Cache::forget('key');

        return redirect('users');

    }

}

Redis Keys Lists:

By default, Redis has 16 databases, numbered from 0 to 15. When you use Redis Facade it uses 0 database. When you use Cache Facade it uses 1 database. This is configured in your application located in the config/database.php configuration file.

Now we can see our stored all the keys from the Redis server from the command line using redis-client. Change the database using select 1-15, by default, it’s 0.

You can easily interact with Redis from the command line interface of your application, without being used by redis-client. For this, you have to create a command file in your application, app\Console\Commands\Redis\RedisCacheKey. Run this command.

NOTE: This command only works if the Cache driver is used.

php artisan make:command Redis/RedisCacheKey

You can use my created command from GitHub Repo: RedisCacheKey

Give some examples for this command:

You can just put the number ex: 0 then enter or 1,2,3,4. If you go to the main menu just write yes / y then enter, or empty entry you are quit from the command line interface.

  • [0] Lists
    • Showing all the keys list stored in the redis cache server.
  • [1] Search for a specific key, suppose you have multiple keys like user:1, user:2, and other keys available in redis cache server. When you search for a key, just select 1 and write the key name (ex: user) that is searching for you.
  • [2] If you delete specific keys from redis server,  so that’s time you can use option 2 and just enter the key number deleted from redis cache server.
  • [3] If you remove all the keys from redis cache server just select option 3, then write yes if delete all the keys.
  • [4] quit from the command line interface.

Conclusion:

Redis is an ultra-fast in-memory key-value data store. Supports strings, numbers, lists, hashes,sets, sorted sets, and publish/subscribe messaging. You can utilize Redis for caching, session storage, queues, broadcasting, and other functionality within your Laravel application. Overall, Redis is a versatile and powerful tool used by developers for various purposes, including caching, real-time analytics, messaging, and more.

The post Redis Integration with Laravel appeared first on Riseup Labs.



This post first appeared on Blog, please read the originial post: here

Share the post

Redis Integration with Laravel

×