php实现一致性hash算法|crc32|md5

<?php

class ConsistentHash{
	
	private $virtual = 10;
	
	protected $serverList = array();
	
	protected $serverNode = array();
	
	protected function getHash($key){
		return sprintf("%u", crc32(md5($key)));	
	}
	
	public function addServer($server){
		for($i = 1; $i <= $this->virtual; $i ++){
			$index = $this->getHash($server."@".$i);
			$this->serverList[$index] = $server;
			$this->serverNode[$server][] = $index;	
		}
		ksort($this->serverList, SORT_NUMERIC);
		return $this;	
	}
	
	public function getServer($key){
		$point = $this->getHash($key);
		$server = current($this->serverList);
		foreach($this->serverList as $index => $value){
			if($point >= $index){
				$server = $value;
			}
		}
		reset($this->serverList);
		return $server;
	}
	
	public function subServer($server){
		if(isset($this->serverNode[$server])){
			foreach($this->serverNode[$server] as $index){
				unset($this->serverList[$index]);	
			}
			unset($this->serverNode[$server]);
		}
		return $this;
	}
		
}


$data = new ConsistentHash;
$data->addServer("192.168.1.1")->addServer("192.168.1.2")->addServer("192.168.1.3")->addServer("192.168.1.4")->addServer("192.168.1.5")->addServer("192.168.1.6")->addServer("192.168.1.7")->addServer("192.168.1.8")->addServer("192.168.1.9")->addServer("192.168.1.10");

print_r($data);

echo $data->getServer("data1");
echo PHP_EOL;
echo $data->getServer("data2");
echo PHP_EOL;
echo $data->getServer("data3");
echo PHP_EOL;
echo $data->getServer("data4");
echo PHP_EOL;
echo $data->getServer("data5");
echo PHP_EOL;
echo $data->getServer("data6");
echo PHP_EOL;
echo $data->getServer("data7");
echo PHP_EOL;
echo $data->getServer("data8");
echo PHP_EOL;
echo $data->getServer("data9");
echo PHP_EOL;
echo $data->getServer("data10");
echo PHP_EOL;
echo $data->getServer("data11");



$data->subServer("192.168.1.4")->subServer("192.168.1.2")->subServer("192.168.1.3")->subServer("192.168.1.1");

echo PHP_EOL.PHP_EOL.PHP_EOL.PHP_EOL.PHP_EOL.PHP_EOL.PHP_EOL.PHP_EOL;

echo $data->getServer("data1");
echo PHP_EOL;
echo $data->getServer("data2");
echo PHP_EOL;
echo $data->getServer("data3");
echo PHP_EOL;
echo $data->getServer("data4");
echo PHP_EOL;
echo $data->getServer("data5");
echo PHP_EOL;
echo $data->getServer("data6");
echo PHP_EOL;
echo $data->getServer("data7");
echo PHP_EOL;
echo $data->getServer("data8");
echo PHP_EOL;
echo $data->getServer("data9");
echo PHP_EOL;
echo $data->getServer("data10");
echo PHP_EOL;
echo $data->getServer("data11");

 

转载于:https://my.oschina.net/andyhua/blog/3017624

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值