Search code examples
phpredispredisredis-sentinel

PHP predis connect to Redis Sentinel


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.


Solution

  • 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
    }