zoukankan      html  css  js  c++  java
  • 一致性哈希算法PHP测试片段

    <?php
    header('Content-type: text/html; charset=utf8');
    # 抽象接口
    interface hash{
    public function _hash($str);
    }
    interface distribution{
    public function lookup($key);
    }

    # hash 算法实例
    class Consistent implements hash,distribution {
    protected $point_num = 64;
    protected $posi = array();
    protected $server;

    #计算一个hash值
    public function _hash($str){
    return sprintf('%u',crc32($str));
    }

    # 计算key分布到的服务器
    public function lookup($key){
    foreach($this->posi as $k=>$v){
    if ($this->_hash($key) <= $k ){
    $this->server = $v;
    break;
    }
    }
    return $this->server;
    }

    # 添加服务节点
    public function addServer($server){
    for ($i=1;$i<=$this->point_num;$i++){
    $this->posi[$this->_hash($server.'_'.$i)] = $server;
    }
    $this->sortPosi();
    }

    #排序定位点
    public function sortPosi(){
    ksort($this->posi);
    }

    #打印定位点
    public function printPosi(){
    echo '<pre>';
    print_r($this->posi);
    }
    }

    $hash = new Consistent();
    $hash->addServer('a');
    $hash->addServer('b');
    $hash->addServer('c');

    #test hash
    $key = 'abc';
    $server = $hash->lookup($key);
    echo $key.'对应的服务器是:'.$Server.' &nbsp;&nbsp;对应的hash值是:'.$hash->_hash($key);
    echo '<hr />';
    $hash->printPosi();

  • 相关阅读:
    蓝桥杯 算法训练 ALGO-118 连续正整数的和
    迭代器和生成器
    字符串格式化
    python 赋值 深浅拷贝
    web.py
    urlib2 标准代码
    left menu
    tab menu
    modal html
    emmet使用
  • 原文地址:https://www.cnblogs.com/shengy/p/7457068.html
Copyright © 2011-2022 走看看