Consistency hashing algorithm PHP test fragment

Source: Internet
Author: User

<?php
Header (' content-type:text/html; Charset=utf8 ');
# abstract Interface
Interface hash{
Public Function _hash ($STR);
}
Interface distribution{
Public Function lookup ($key);
}

# Hash Algorithm Example
Class consistent implements Hash,distribution {
protected $point _num = 64;
Protected $posi = Array ();
protected $server;

#计算一个hash值
Public Function _hash ($STR) {
Return sprintf ('%u ', CRC32 ($STR));
}

# Compute the server to which the key is distributed
Public Function Lookup ($key) {
foreach ($this->posi as $k = + $v) {
if ($this->_hash ($key) <= $k) {
$this->server = $v;
Break
}
}
return $this->server;
}

# Add Service Node
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. ' The corresponding server is: '. $Server. ' &nbsp;&nbsp; the corresponding hash value is: '. $hash->_hash ($key);
echo ' $hash->printposi ();

Consistency hashing algorithm PHP test fragment

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.