Laravel: How to Check Redis Availability?
Asked Answered
D

6

7

How can i check the availability of Redis connection in Laravel 5.4. I tried below code, but getting an exception with ping line. How can i do, if Redis is not connected than do something else to avoid exception?

No connection could be made because the target machine actively refused it. [tcp://127.0.0.1:6379]

use Redis;

class SocketController extends Controller
{
    public function sendMessage(){
        $redis = Redis::connection();

        if($redis->ping()){
            print_r("expression");
        }
        else{
            print_r("expression2");
        }
    }
}

Also tried this:

$redis = Redis::connection();
        try{
            $redis->ping();
        } catch (Exception $e){
            $e->getMessage();
        }

But unable to catch exception

Demona answered 9/8, 2017 at 6:14 Comment(0)
P
12

if you are using predis , then it will throw Predis\Connection\ConnectionException

Error while reading line from the server. [tcp://127.0.0.1:6379] <--when redis is not connected

so catch that Exception, you will get your redis is connected or not .

use Illuminate\Support\Facades\Redis;

    public function redis_test(Request $request){
    try{
        $redis=Redis::connect('127.0.0.1',3306);
        return response('redis working');
    }catch(\Predis\Connection\ConnectionException $e){
        return response('error connection redis');
    }
Plumbing answered 13/2, 2019 at 6:19 Comment(1)
It's returning "redis working in every case" whatever I put the host and portEquilibrant
A
9
<?php

namespace App\Helpers;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class ConnectionChecker
{
    public static function isDatabaseReady($connection = null)
    {
        $isReady = true;
        try {
            DB::connection($connection)->getPdo();
        } catch (\Exception $e) {
            $isReady = false;
        }

        return $isReady;
    }

    public static function isRedisReady($connection = null)
    {
        $isReady = true;
        try {
            $redis = Redis::connection($connection);
            $redis->connect();
            $redis->disconnect();
        } catch (\Exception $e) {
            $isReady = false;
        }

        return $isReady;
    }
}  

I created a helper class to check redis and db connection

Airplane answered 19/3, 2019 at 19:49 Comment(2)
For the $redis->connect method I had to supply the HOST + PORT otherwise, it worked well.Annals
There should be an associated example for the usage of this helper.Grader
O
2

Make sure redis is installed

$ sudo apt-get update 
$ sudo apt-get upgrade
$ sudo apt-get  install redis-server

To test that your service is functioning correctly, connect to the Redis server with the command-line client:

redis-cli

In the prompt that follows, test connectivity by typing:

ping

You should see:

Output

PONG

Install Laravel dependencies

composer require predis/predis

https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-redis-on-ubuntu-16-04

https://askubuntu.com/questions/868848/how-to-install-redis-on-ubuntu-16-04

Outward answered 9/8, 2017 at 6:21 Comment(4)
Yes i can do ping in redis-cli and i can also connect with redis through laravel but i don't know how to check that redis is connected or not so that i can do other stuffDemona
Because i get exception and application stop if redis is not connectedDemona
No connection could be made because the target machine actively refused it. [tcp://127.0.0.1:6379] means you cannot connect there from any means,Outward
The question is another. The answer is one that does not contribute anything except saying "I know something."Bibliofilm
C
2

In your constructor you can check redis status connection like this:

/**
 * RedisDirectGeoProximity constructor.
 * @throws RedisConnectionException
 */
public function __construct()
{
    try
    {
        $this->redisConnection = Redis::connection('default');
    }
    catch ( Exception $e )
    {
        throw new RedisConnectionException([
            'message' => trans('messages.redis.fail'),
            'code' => ApiErrorCodes::REDIS_CONNECTION_FAIL
        ]);
    }
}

and in your exception :

namespace App\Exceptions\Redis;

/**
 * Class RedisConnectionException
 * @package App\Exceptions\Redis
 */
 class RedisConnectionException extends \Exception
 {
     /**
      * RedisConnectionException constructor.
      * @param array $options
      */
      public function __construct(array $options = [])
      {
          parent::__construct($options);
      }
 }
Countrified answered 20/2, 2019 at 13:11 Comment(0)
A
0

This files is routes/console.php and here I tested my "hello world" for Redis server it worked fine. I created an artisan command.

php artisan vibhore

will do all the redis related experiment here.

use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Redis;
//use Illuminate\Support\Facades\Cache;

Artisan::command('vibhore', function () {
    //$this->comment(Inspiring::quote());
    echo "vibhore is saying hello world by making his own command";//i got success in this. 
    //Redis::set('vj_key', 'vj_value');
    //Redis::del('vj_key');
    //Redis::expire('key', 30 * 60);//setting and expire time to redis. 
    //Cache::put('vj_key', 'vj_value', 30);//it will be alive for only 30 seconds. 
    //echo Cache::get('vj_key');
    //echo Redis::get('vj_key');
})->purpose('Display an vibhore quote');

Later on I learned more about where to use Redis (in middleware) that in routes/web.php, while defining the routes, we can use them as

Route::get('/test-redis', function () {
    // Store value in cache
    //Cache::put('vj_key2', 'vj_value2', 30);

    // Retrieve value from cache
    //$cacheValue = Cache::get('vj_key2');

    // Directly get value from Redis
    //Redis::set('vj_key2','vj_setvalue');
    //$redisValue = Redis::get('vj_key2');
    //Redis::del('vj_key2');
    //Redis::expire('key', 30 * 60);
    return "Cache value: $cacheValue, Redis value: $redisValue";
});
Acidify answered 27/5 at 16:37 Comment(0)
S
-1

please try with catch (\Exception $e) incl. backslash

Shirline answered 9/4, 2018 at 7:38 Comment(1)
While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.Fletafletch

© 2022 - 2024 — McMap. All rights reserved.