Search code examples
phpredisphpredis

redis connection inside infinite loop


I'm creating a redis connection using phpredis client

$redis = new Redis();
$redis->pconnect(loclahost, 6336, 2) ;
$redis->select(15);

Now I used the $redis object inside an infinite loop.

while(true){
   ///using redis connection object.
}

Around 54 such individual processes were running but once or twice in a day I get an error like "read error on connection".

Please help me to fix it.


Solution

  • I would think something like this would work. NOTE I have not tested this, and I have not written PHP in a pretty long time.

    function redisConnection() {
        try {
            $redis = new Redis()
            $redis->pconnect(localhost, 6336, 2);
            $redis->select(15);
            $redis->ping();
            return $redis;
        } catch (Exception $e) {
            throw new Exception("Can not connect: " . $e->getMessage());
        }
    }
    
    $redis = redisConnection();
    while (true) {
        try {
            $redis->ping();
        } catch {
            $redis = redisConnection();
        }
        // Rest of code
    }