0

I've set up a new PHP predis connection to a redis server using the documented code. I can verify it's connected ok, but I don't know how to simply test if the connection exists.

$options = array(
    'scheme' => 'tcp',
    'host' => '127.0.0.1',
    'port' => $port,
    'instance' => 'myinstance',
    'timeout' => '0.100' // possibly add this to connections?
);

$sentinels = [
    "tcp://{$options['host']}:{$options['port']}?timeout={$options['timeout']}",
];

$connection = new Predis\Client($sentinels, [
    'replication' => 'sentinel',
    'service' => $options['instance'],
]);

if ($connection->isConnected() === true) {
// undocumented-- I don't think this works?
    echo "connected";
} else {
    echo "failed"; // this is what gets echoed
}

Is there a method to test if the connection is good short of actually reading / writing to it? isConnected() doesn't appear to work.

user101289
  • 9,888
  • 15
  • 81
  • 148
  • Looking at the source code it uses exceptions so maybe use try/catch to wrap the Client instantiation and see what happens with invalid options? – TheDrot Jun 30 '16 at 16:16
  • @TheDrot-- good thought, but apparently all it does is instantiate the `Client`, it doesn't make any connection until a read / write is attempted, so you can provide garbage IP and service name and it accepts it with no problems – user101289 Jun 30 '16 at 16:28
  • 1
    Then connect to server first `$connection->connect();` before checking if it's connected. – TheDrot Jun 30 '16 at 17:06
  • @TheDrot-- that looks like it works-- post as an answer and I'll accept. Thanks! – user101289 Jun 30 '16 at 17:46

1 Answers1

0

As suggested by @drot:

$options = array(
    'scheme' => 'tcp',
    'host' => '127.0.0.1',
    'port' => $port,
    'instance' => 'myinstance',
    'timeout' => '0.100' // possibly add this to connections?
);

$sentinels = [
   "tcp://{$options['host']}:{$options['port']}?timeout={$options['timeout']}",
];

$connection = new Predis\Client($sentinels, [
    'replication' => 'sentinel',
    'service' => $options['instance'],
]);

// do this: 
$connection->connect();

if ($connection->isConnected() === true) {
    // undocumented-- I don't think this works?
    echo "connected";
} else {
    echo "failed"; // this is what gets echoed
}
user101289
  • 9,888
  • 15
  • 81
  • 148