Skip to content

Instantly share code, notes, and snippets.

@nrk
Created April 18, 2011 17:50
Show Gist options
  • Select an option

  • Save nrk/925787 to your computer and use it in GitHub Desktop.

Select an option

Save nrk/925787 to your computer and use it in GitHub Desktop.
Dirty trick to get a transaction instance out of a cluster of connections by using a particular key tag.
<?php
// Using Predis 0.6
require 'Predis.php';
$clusterClient = new Predis\Client(array(/* array of servers */));
// We use a fake command (e.g. GET) to obtain the actual connection out of a cluster
// that is responsible for our particular key tag (or a key, but *only* that one key).
$fakeCommand = $clusterClient->createCommand('get', array("{ONLY_THE_KEY_TAG}"));
$singleConnection = $clusterClient->getConnection()->getConnection($fakeCommand);
// Unfortunately, the only way to create a new client instance for a single
// connection that participates to a cluster is by using a method the works
// only with connection aliases.
$alias = $singleConnection->getParameters()->alias;
if (!isset($alias)) {
// It's just a dirty trick after all...
throw new Exception("Whooops");
}
$transaction = $clusterClient->getClientFor($alias)->multiExec();
/* do stuff with $transaction */
<?php
// Using Predis 0.7
require 'predis_autoloader.php';
$clusterClient = new Predis\Client(array(/* array of servers */));
// We use a fake command (e.g. GET) to obtain the actual connection out of a cluster
// that is responsible for our particular key tag (or a key, but *only* that one key).
$fakeCommand = $clusterClient->createCommand('get', array("{ONLY_THE_KEY_TAG}"));
$singleConnection = $clusterClient->getConnection()->getConnection($fakeCommand);
// With 0.7.x the constructor of Predis\Client can also accept instances
// of a connection class, so it's much more clean like this.
$singleClient = new Predis\Client($singleConnection, $clusterClient->getOptions());
$transaction = $singleClient->multiExec();
/* do stuff with $transaction */
<?php
// Using Predis 0.7 (After Git commit 880d2d2)
require 'predis_autoloader.php';
$clusterClient = new Predis\Client(array(/* array of servers */));
// After Git commit 880d2d2, the default cluster connection class gives the ability
// to get a connection out of a cluster using a key (compatible with key tagging).
$singleConnection = $clusterClient->getConnection()->getConnectionByKey("FULL_KEY_WITH_KEYTAG");
// With 0.7.x the constructor of Predis\Client can also accept instances
// of a connection class, so it's much more clean like this.
$singleClient = new Predis\Client($singleConnection, $clusterClient->getOptions());
$transaction = $singleClient->multiExec();
/* do stuff with $transaction */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment