一致性hash php
<?phprequire_once 'flexihash.php';
error_reporting(0);
Class CiHashSvc
{
public $hash = null;
public $memcache = null;
public $connectPool = null;
public function __construct()
{
$this->hash = new Flexihash();
}
public function addServers( $servers )
{
foreach ($servers as $server)
{
$node = $server;
$this->connectPool[$node] = false;
$targets[] = $node;
}
$this->hash->addTargets( $targets );
}
public function set( $key, $value )
{
$nodes = $this->hash->lookupList( $key, count( $this->connectPool ) );
foreach ($nodes as $node)
{
if (!$this->connectPool[$node])
{
$this->connectPool[$node] = $node;
}
if ($this->connectPool[$node])
{
echo "set key [$key] => value [$value] in node [$node]<br/>";
return $node;
}
}
return false;
}
public function get( $key )
{
$nodes = $this->hash->lookupList( $key, count( $this->connectPool ) );
foreach ($nodes as $node)
{
if (!$this->connectPool[$node])
{
$this->connectPool[$node] = $node;
}
if ($this->connectPool[$node])
{
echo "get key [$key] in node [$node]<br/>";
return $node;
}
}
return false;
}
}
$data = array();
//$config = array('1:1','2:2','3:3');
$config = array('2:2','3:3','4:4');
$beginTime = microtime(true);
$cls = newCiHashSvc();
$cls->addServers($config);
for($i = 1;$i < 5000; $i++){
$cls->set($i,$i);
$idx = $cls->get($i);
$data[$idx] += 1;
}
$diff = -$beginTime + microtime(true);
echo "total time : [$diff]<br/>";
var_dump($data);
页:
[1]