欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

取余和一致性hash算法

程序员文章站 2024-03-19 21:40:16
...

配置文件

<?php
$s = [];
$ss['A'] = ['host'=>'localhost','11211'];
$ss['B'] = ['host'=>'localhost','11212'];
$ss['C'] = ['host'=>'localhost','11213'];
$ss['D'] = ['host'=>'localhost','11214'];
$ss['E'] = ['host'=>'localhost','11215'];

取余算法

<?php
/**
* memcached 取模分布式算法
*/
interface hasher{
    public function _hash($str);
}

interface distribution{
    public function lookup($key);
}

class Moder implements hasher,distribution{
	protected $_ser = [];
	protected $_num = 0;//服务器数

	//获取整数值
	public function _hash($str){
		return sprintf('%u',crc32($str));		

	}

	public function lookup($key){
		$index = $this -> _hash($key) % $this->_num;
		return $this->_ser[$index];	
	}
	//添加服务器
	public function addNode($s){
		$this->_ser[] = $s;
		$this->_num +=1;
	}
	//删除节点
	public function delNode($s){
		foreach($this ->_ser as $k => $v){
			if($s == $v){
				unset($this_ser[$k]);
			}
		}
		$this->_num -= 1;
		$this->_ser = array_merge($this->_ser);
	}

}

$m = new Moder();
$m ->addNode('a');
$m ->addNode('b');
$m ->addNode('c');
$m ->addNode('d');

for($i = 1;$i <=100; $i ++){
	$key = 'key_'.$i;
	echo $key,'--->',$m -> lookup($key),PHP_EOL;
}



一致性hash算法

<?php
date_default_timezone_set('PRC');
interface hasher{
    public function _hash($str);
}

interface distribution{
    public function lookup($key);
}

class Cons implements hasher,distribution{
	protected $nodes = [];
	protected $points = [];
	protected $_mul = 64;//虚拟节点数

	//获取无符号整数值
	public function _hash($str){
		return sprintf('%u',crc32($str));
	}
	//分配节点
	public function lookup($key){
		$postion = $this->_hash($key);//获取键值的整数值
		reset($this->points);
		$neddle = key($this->points);
		foreach($this -> points as $p => $v){
			if($postion <=$p){
				$neddle = $p;
				break;
			}
		}
		return $neddle.'--->'.$this ->points[$neddle];
	}
	//添加节点
	public function addNode($node){
		$this ->nodes[$node] = [];
		for($i = 0;$i< $this->_mul;$i +=1){
			$point = $node .'_'.$i;
			$point = $this ->_hash($point);//虚拟节点转为数字
			$this -> points[$point] = $node;
			$this ->nodes[$node][] = $point;
			$this -> resort();
		}
	}

	//排序
	public function resort(){
		 ksort($this->points);
	}
	//删除节点
	public function delNode($node){
		foreach($this->nodes[$node] as $p){
			unset($this->points[$p]);//清除虚拟节点
		}
		unset($this->nodes[$node]);//清除节点
	}
	
}

$cons = new cons();
$cons -> addNode('A');
$cons -> addNode('B');
$cons -> addNode('C');
$cons -> addNode('D');
$cons -> addNode('E');
echo $cons -> _hash('name'),'--fall in节点--',$cons -> lookup('name'),PHP_EOL;
echo $cons -> _hash('title'),'--fall in节点--',$cons -> lookup('title'),PHP_EOL;
echo $cons -> _hash('aaaa'),'--fall in节点--',$cons -> lookup('aaaa'),PHP_EOL;
print_r($cons);