See this article and this issue for more details about the Nrk\AliasBasedHashRing
class and the reasons behind it.
Created
August 20, 2011 16:44
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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