Example #1
0
    /**
     * 删除节点
     * @param $key
     */
    public function remove_node($key)
    {
        $hash = $this->mHash($key);
        if (isset($this->_nodes[$hash])) {
            unset($this->_nodes[$hash]);
        }
        //重新排序
        krsort($this->_nodes, SORT_NUMERIC);
    }
    /**
     * 获取节点
     * @param $key
     * @return mixed
     */
    public function get_node($key)
    {
        $hash = $this->mHash($key);
        foreach ($this->_nodes as $pos => $node) {
            if ($pos >= $hash) {
                return $node;
            }
        }
        return $this->_nodes[$pos];
    }
}
$hash = new ConsistentHash();
echo dechex($hash->mHash("testA123")) . "\n";
$map = new ConsistentHashNode($hash);
for($i = 0; $i < 10; ++$i){
   $map->put('key' . $i, 'value' . $i);
}
$hash->add(new IdentNode('hoge4'));
for($i = 10; $i < 20; ++$i){
   $map->put('key' . $i, 'value' . $i);
}
$hash->add(new IdentNode('hoge5'));
for($i = 30; $i < 40; ++$i){
   $map->put('key' . $i, 'value' . $i);
}

$allKeys = $map->keys();
foreach($hash->getNodes() as $node){
   $keys = $node->keys();
   echo 'node(', (count($keys) / count($allKeys)) * 100, '%):', $node->getName(), ', keys:', join(',', $keys), PHP_EOL;
}
*/
$hash = new ConsistentHash(new HashMD5Integer(), 32);
$hash->add(new IdentNode('hoge1'));
$hash->add(new IdentNode('hoge2'));
$hash->add(new IdentNode('hoge3'));
$hash->add(new IdentNode('hoge4'));
$map = new ConsistentHashNode($hash);
for ($i = 0; $i < 10; ++$i) {
    $map->put(chr(65 + $i), $i);
}
foreach ($hash->getNodes() as $node) {
    echo $node->getName(), ':', join(',', $node->keys()), PHP_EOL;
}
Example #3
0
    {
        $hash_value = $this->my_hash($key);
        //°´keyÅÅÐò
        if (!$this->is_sorted) {
            krsort($this->slots_arr, SORT_NUMERIC);
            $this->is_sorted = true;
        }
        foreach ($this->slots_arr as $pos => $slot) {
            if ($hash_value >= $pos) {
                return $slot;
            }
        }
        return $this->slots_arr[count($this->slots_arr) - 1];
    }
}
$c_hash = new ConsistentHash();
$c_hash->hash_add_slot('slot1');
$c_hash->hash_add_slot('slot2');
/*
$c_hash->hash_add_slot('slot3');
$c_hash->hash_add_slot('slot4');
$c_hash->hash_add_slot('slot5');
*/
echo "key1 in " . $c_hash->lookup('key1') . "\n";
echo "key2 in " . $c_hash->lookup('key2') . "\n";
echo "key3 in " . $c_hash->lookup('key3') . "\n\n";
$c_hash->hash_delete_slot('slot2');
echo "key1 in " . $c_hash->lookup('key1') . "\n";
echo "key2 in " . $c_hash->lookup('key2') . "\n";
echo "key3 in " . $c_hash->lookup('key3') . "\n\n";
$c_hash->hash_add_slot('slot6');