Skip to content

Instantly share code, notes, and snippets.

@nrk
Created August 20, 2011 16:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nrk/1159319 to your computer and use it in GitHub Desktop.
Save nrk/1159319 to your computer and use it in GitHub Desktop.
Use a node alias instead of the ip:port pair when calculating the hash of a node in a cluster with Predis.
<?php
namespace Nrk;
use Predis\Distribution\HashRing;
// NOTE: this class won't work with a version of Predis prior to commit b30f495
class AliasBasedHashRing extends HashRing {
public function add($node, $weight = null) {
$parameters = $node->getParameters();
if (!$parameters->isSetByUser('alias')) {
throw new \InvalidArgumentException(
"The 'alias' property must be set for {$node} to use " .
"this kind of distribution strategy"
);
}
parent::add($node, $weight);
}
protected function getNodeHash($nodeObject) {
return $nodeObject->getParameters()->alias;
}
}

See this article and this issue for more details about the Nrk\AliasBasedHashRing class and the reasons behind it.

<?php
require 'autoload.php';
require 'AliasBasedHashRing.php';
use Predis\Network\PredisCluster;
use Nrk\AliasBasedHashRing;
// ------------------------------------------------------------------------- //
const UNUSED_DB = 15;
$servers = array(
array(
'host' => '192.168.1.33',
'port' => 6379,
'alias' => 'node01',
'database' => UNUSED_DB,
),
array(
'host' => '192.168.1.33',
'port' => 6380,
'alias' => 'node02',
'database' => UNUSED_DB,
),
);
$options = array(
'cluster' => function() {
$distributor = new AliasBasedHashRing();
return new PredisCluster($distributor);
},
);
// ------------------------------------------------------------------------- //
$client = new Predis\Client($servers, $options);
$node01 = $client->getClientFor('node01');
$node01->flushdb();
$node02 = $client->getClientFor('node02');
$node02->flushdb();
for ($i = 1; $i <= 100; $i++) {
$client->set("key:$i", str_pad($i, 3, '0', 0));
$client->get("key:$i");
}
$server1 = $node01->info();
$server2 = $node02->info();
printf("Server '%s' has %d keys while server '%s' has %d keys.\n",
'first', $server1['db'.UNUSED_DB]['keys'], 'second', $server2['db'.UNUSED_DB]['keys']
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment