一致性hash php


<?php
require_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 = new CiHashSvc();
$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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值