<?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. ' the corresponding hash value is: '. $hash->_hash ($key);
echo ' $hash->printposi ();
Consistency hashing algorithm PHP test fragment