Redis Logo

We’re using Redis Sentinel to provide high availability for our Redis deployment. One of the struggles we had as we made this transition was finding a way to get php-resque to connect to Redis Sentinel as well.

By default, php-resque connects to the default port on the local server. If you need to point is somewhere else their documentation provides a single example for setting the server to something else:

<?php
// Required if redis is located elsewhere
Resque::setBackend('localhost:6379');

The quick solution to fix this is would be to use the Credis library to determine what the master is and set the server to that. That doesn’t allow for us to read from the slaves which is a huge benefit to using Sentinel. After digging through the source code, I found that you can pass a function instead of a string to the setBackend function so it can setup the connection. Credis provides a Credis_Sentinel class that allows for a connection to the cluster but is smart enough to split reads and writes and has the same methods so they’re interchangeable. Below is how this works.

<?php
Resque::setBackend(function($database){
    $sentinel = new Credis_Sentinel(new Credis_Client('localhost', 26379));
    $cluster = $sentinel->getCluster('mymaster');
    $cluster->select($database);
    return new Resque_Redis('', null, $cluster);
});