编程语言
首页 > 编程语言> > 一致性哈希算法

一致性哈希算法

作者:互联网

<?php
interface hash
{
    public function _hash($str);
}

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

class Consistent implements hash,distribution
{
    protected $_postion = [];
    protected $_mul = 64;
    
    public function _hash($str){
        return sprintf('%u',crc32($str));
    }
    
    public function lookup($key){
        $point = $this->_hash($key);
        
        //先取圆环上最小的一个节点
        $node = current($this->_postion);
        
        foreach($this->_postion as $k=>$v){
            if($point <= $k){
                $node = $v;
                break;
            }
        }
        
        return $node;
    }
    
    //添加节点
    public function addNode($node){
        for($i = 0;$i<$this->_mul;$i++){
            $this->_postion[$this->_hash($node . '-' . $i)] = $node;
        }
        $this->_sortPos();
    }
    
    //删除节点
    public function delNode($node){
        foreach($this->_postion as $k=>$v){
            if($v == $node){
                unset($this->_postion[$k]);
            }
        }
    }
    
    //排序节点
    protected function _sortPos(){
        ksort($this->_postion,SORT_REGULAR);
    }
    
    public function printPosition(){
        print_r($this->_postion);
    }
}

//添加节点
$con = new Consistent();
$con->addNode('a');
$con->addNode('b');
$con->addNode('c');

//删除节点
$con->delNode('b');

echo '所有的服务器如下<br />';
$con->printPosition();

$key = 'title';
echo '当前的键计算的hash落点是' . $con->_hash($key). '<br />';
echo '应该落在'.$con->lookup($key) .'号服务器';

 

标签:node,hash,key,postion,算法,哈希,一致性,节点,con
来源: https://www.cnblogs.com/nr-zhang/p/10906266.html