memcached快取伺服器一致性雜湊分佈部署類
阿新 • • 發佈:2019-01-02
class FlexHash{ private $server_list = array(); private $is_sort = false; public function add_server($server) { $hash = mhash(MHASH_MD5,$server); if(!isset($this->server_list[$hash])){ $this->server_list[$hash] = $server; } $this->is_sort = false; return true; } public function remove_server($server) { $hash = mhash(MHASH_MD5,$server); if(isset($this->server_list[$hash])){ unset($this->server_list[$hash]); } $this->is_sort = false; return true; } public function look_up($key) { $hash = mhash(MHASH_MD5,$key); if(!$this->is_sort){ krsort($this->server_list,SORT_NUMERIC); $this->is_sort = true; } foreach ($this->server_list as $item => $value) { if($hash >= $value) return $value; } return $this->server_list[count($this->server_list) - 1]; } } //echo $hash = mhash(MHASH_MD5,'1.2.3.4'); $server = new FlexHash(); $server->add_server('1.2.3.4'); $server->add_server('5.6.7.8'); $server->add_server('9.10.11.12'); $server->add_server('13.14.15.16'); $server->add_server('17.18.19.20'); $server->add_server('21.22.23.24'); $server->add_server('25.26.27.28'); echo "save 1 in ".$server->look_up('key1')."<br>"; echo "save 2 in ".$server->look_up('key2')."<br>"; $server->remove_server("21.22.23.24"); echo "save 1 in ".$server->look_up('key1')."<br>"; echo "save 2 in ".$server->look_up('key2')."<br>"; $server->add_server('29.30.31.32'); echo "save 1 in ".$server->look_up('key1')."<br>"; echo "save 2 in ".$server->look_up('key2')."<br>";
簡單記錄下實現的類,各位有則取之。