PHP Classes

File: ConsistentHash.example.php

Recommend this page to a friend!
  Classes of Mudessir Medgitov   Magic Consistent Hash Class   ConsistentHash.example.php   Download  
File: ConsistentHash.example.php
Role: Example script
Content type: text/plain
Description: Example of usage
Class: Magic Consistent Hash Class
Get an hash for a string from an array of values
Author: By
Last change: cleaned up not needed things
Date: 14 years ago
Size: 1,909 bytes
 

Contents

Class file image Download
<?php
   
require_once("ConsistentHash.class.php");

    function
getmicrotime() {
       list(
$usec, $sec) = explode(" ", microtime());
       return ((float)
$usec + (float)$sec);
    }
   
   
$servers = array(
       
'1.1.1.1',
       
'1.1.1.2',
       
'1.1.1.3',
       
'1.1.1.4',
       
'1.1.1.5',
       
'1.1.1.6',
       
'1.1.1.7',
       
'1.1.1.8',
       
'1.1.1.9'
   
);
   
   
$objCHash = new ConsistentHash($servers);
   
   
// lets look how all keys are loadbalanced in hash array
   
$start_time = getmicrotime();
   
   
$counters = array();
    for (
$i=0; $i<500; $i++){
       
$id = mt_rand(1000,9999999);
       
//$id = $i;
       
$host = $objCHash->Lookup($id,1);
       
       
$counters[$host]++;
    }
    echo
"How they loadbalanced:<br>\n";
    foreach (
$counters as $k=>$v){
        echo
$k." - key count:".$v."<br>\n";
    }
    echo
"<br>\n";echo "<br>\n";
   
   
$end_time = getmicrotime();
   
    echo
"time:".($end_time-$start_time);

   
  
   
// example of usage:
    // $data = 'data for cahing';
    // $key = md5($data) - usually key makes by this way
    // $host = $objCHash->Lookup($key);
    // here we got hostname of needed cache server, now we can use native memcached class to connect to it
    // $memcache = new Memcache;
    // $connect = $memcache->connect($host , 11212, 1);
    // $memcache->set($key,$data);
   
   
$start_time = getmicrotime();
   
$counters = array();
    for (
$i=0; $i<500; $i++){
       
$id = mt_rand(1000,9999999);
       
//$id = $i;
       
$host = (array)$objCHash->Lookup($id,2); // will return 2 items from hash array.
        //$host = implode(':',$host);
       
echo "[".$i."] - ".implode('|',$host)." : ".$id."<br>\n";
       
    }
   
$end_time = getmicrotime();
   
  
   
    echo
"time:".($end_time-$start_time);