Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: How to Check Redis Availability?

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

like image 658
MTA Avatar asked Dec 03 '22 21:12

MTA


2 Answers

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');
    }
like image 145
Saurabh Mistry Avatar answered Feb 19 '23 17:02

Saurabh Mistry


<?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

like image 34
AXE Avatar answered Feb 19 '23 18:02

AXE