4

In case of Redis failure, is that possible to instruct php predis (https://github.com/nrk/predis) to continue and to not die?

I have Redis to handle application cache, but the application can run without cache, it just hits the database heavier. I prefer to fallback to database then have the application dying. I cant find a way to instruct predis to continue on fail.

I thought in set the connection limit to about 5 seconds, if it cant connect to Redis the application should go on.

Is this possible?

Fatal error: Uncaught Predis\Connection\ConnectionException: Operation timed out [tcp://128.0.0.1:6379]
AFRC
  • 902
  • 3
  • 9
  • 27

1 Answers1

7

You can catch the connection exception and fallback to your database. Example:

try {
    return $predis->get('foobar');
} catch(\Predis\Connection\ConnectionException $ex) {
    // fallback to database call
}

For cleaner code wrap the database/redis call in a new class that abstracts away the actual connection, that way your calling code doesn't need to care which datasource was used.

Leif Högberg
  • 378
  • 1
  • 5
  • 3
    Also, instead of `$predis->get('foobar');` you can do `$predis->ping();` which means you don't have to know any keys' names. – Redzarf Nov 19 '19 at 11:50