/**
* Flexihash-a simple consistent hashing implementation for PHP.
*
* The MIT License
*
* Copyright (c) Paul Annesley
*
* Permission is hereby granted, free of charge, to all person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* In the software without restriction, including without limitation the rights
* To use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* Copies of the software, and to permit persons to whom the software are
* Furnished to does so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall is included in
* All copies or substantial portions of the software.
*
* The software is provided ' as is ', without WARRANTY of any KIND, EXPRESS OR
* implied, including but not LIMITED to the warranties of merchantability,
* FITNESS for A particular PURPOSE and noninfringement. In NO EVENT shall the
* AUTHORS or COPYRIGHT holders be liable for any CLAIM, damages or other
* Liability, WHETHER in a ACTION of contract, TORT OR OTHERWISE, arising from,
* Out of OR in CONNECTION with the software or the use or other dealings in
* The software.
*
* @author Paul Annesley
* @link http://paul.annesley.cc/
* @copyright Paul Annesley, 2008
* @comment by Myz (Http://blog.csdn.net/mayongzhan)
*/
/**
* A simple consistent hashing implementation with pluggable hash algorithms.
*
* @author Paul Annesley
* @package Flexihash
* @licence http://www.opensource.org/licenses/mit-license.php
*/
Class Flexihash
{
/**
* The number of positions to hashes each target to.
*
* @var int
* @comment the number of virtual nodes to solve the problem of uneven distribution of nodes
*/
Private $_replicas = 64;
/**
* The hash algorithm, encapsulated in a flexihash_hasher implementation.
* @var Object Flexihash_hasher
* @comment using the hash method: MD5,CRC32
*/
Private $_hasher;
/**
* Internal counter for the current number of targets.
* @var int
* @comment Node Register
*/
Private $_targetcount = 0;
/**
* Internal Map of positions (hash outputs) to targets
* @var Array {position = target, ...}
* @comment position corresponding node, used in lookup to determine the node to be accessed based on location
*/
Private $_positiontotarget = Array ();
/**
* Internal Map of targets to lists of positions, that target was hashed to.
* @var Array {target = [position, position, ...], ...}
* @comment node corresponding location for deleting nodes
*/
Private $_targettopositions = Array ();
/**
* Whether the internal map of positions to targets is already sorted.
* @var Boolean
* @comment is sorted
*/
Private $_positiontotargetsorted = false;
/**
* Constructor
* @param object $hasher flexihash_hasher
* @param int $replicas Amount of positions to hashes each target to.
* @comment constructor, determine the hash method to be used and the number of desired nodes, the more the number of virtual nodes, the more evenly distributed, but the program's distributed operation is more slow
*/
Public function __construct (flexihash_hasher $hasher = null, $replicas = NULL)
{
$this->_hasher = $hasher? $hasher: New Flexihash_crc32hasher ();
if (!empty ($replicas)) $this->_replicas = $replicas;
}
/**
* Add a target.
* @param string $target
* @chainable
* @comment add nodes, distribute nodes to multiple virtual locations based on the number of virtual nodes
*/
Public Function AddTarget ($target)
{
if (Isset ($this->_targettopositions[$target]))
{
throw new Flexihash_
Exception("Target ' $target ' already exists.");
}
$this->_targettopositions[$target] = array ();
Hash the target into multiple positions
for ($i = 0; $i < $this->_replicas; $i + +)
{
$position = $this->_hasher->hash ($target. $i);
$this->_positiontotarget[$position] = $target; Lookup
$this->_targettopositions[$target] []= $position; Target removal
}
$this->_positiontotargetsorted = false;
$this->_targetcount++;
return $this;
}
/**
* Add a list of targets.
* @param array $targets
* @chainable
*/
Public Function addtargets ($targets)
{
foreach ($targets as $target)
{
$this->addtarget ($target);
}
return $this;
}
/**
* Remove a target.
* @param string $target
* @chainable
*/
Public Function Removetarget ($target)
{
if (!isset ($this->_targettopositions[$target]))
{
throw new Flexihash_
Exception("Target ' $target ' does not exist.");
}
foreach ($this->_targettopositions[$target] as $position)
{
unset ($this->_positiontotarget[$position]);
}
unset ($this->_targettopositions[$target]);
$this->_targetcount--;
return $this;
}
/**
* A List of all potential targets
* @return Array
*/
Public Function Getalltargets ()
{
Return Array_keys ($this->_targettopositions);
}
/**
* Looks up the target for the given resource.
* @param string $resource
* @return String
*/
Public Function lookup ($resource)
{
$targets = $this->lookuplist ($resource, 1);
if (empty ($targets)) throw new Flexihash_
Exception(' No targets exist ');
return $targets [0];
}
/**
* Get a list of targets for the resource, in order of precedence.
* Up to $requestedCount targets is returned, less if there is fewer in total.
*
* @param string $resource
* @param int $requestedCount The length of the list to return
* @return Array List of targets
* @comment Find the node that corresponds to the current resource,
* The node is empty and returns NULL, and only one node returns that node.
* Hash the current resource, sort all the positions, and find the location of the current resource on the ordered position column.
* When all is not found, the location of the resource is identified as the first of the ordered position (forming a ring)
* Returns the found node
*/
Public Function LookupList ($resource, $requestedCount)
{
if (! $requestedCount)
throw new Flexihash_
Exception(' Invalid count requested ');
Handle No targets
if (Empty ($this->_positiontotarget))
return Array ();
Optimize single target
if ($this->_targetcount = = 1)
Return Array_unique (Array_values ($this->_positiontotarget));
Hash resource to a position
$resourcePosition = $this->_hasher->hash ($resource);
$results = Array ();
$collect = false;
$this->_sortpositiontargets ();
Search values above the Resourceposition
foreach ($this->_positiontotarget as $key = $value)
{
Start collecting targets after passing resource position
if (! $collect && $key > $resourcePosition)
{
$collect = true;
}
Only collect the first instance of any target
if ($collect &&!in_array ($value, $results)
{
$results []= $value;
}
Return when enough results, or list exhausted
if (count ($results) = = $requestedCount | | count ($results) = = $this->_targetcount)
{
return $results;
}
}
Loop to Start-search values below the Resourceposition
foreach ($this->_positiontotarget as $key = $value)
{
if (!in_array ($value, $results))
{
$results []= $value;
}
Return when enough results, or list exhausted
if (count ($results) = = $requestedCount | | count ($results) = = $this->_targetcount)
{
return $results;
}
}
Return results after iterating through both "parts"
return $results;
}
Public Function __tostring ()
{
Return sprintf (
'%s{targets:[%s]} ',
Get_class ($this),
Implode (', ', $this->getalltargets ())
);
}
// ----------------------------------------
Private methods
/**
* Sorts the internal mapping (positions to targets) by position
*/
Private Function _sortpositiontargets ()
{
Sort by key (position) if not already
if (! $this->_positiontotargetsorted)
{
Ksort ($this->_positiontotarget, sort_regular);
$this->_positiontotargetsorted = true;
}
}
}
/**
* Hashes given values into a sortable fixed size address space.
*
* @author Paul Annesley
* @package Flexihash
* @licence http://www.opensource.org/licenses/mit-license.php
*/
Interface Flexihash_hasher
{
/**
* Hashes the given string into a 32bit address space.
*
* Note that the output is more than 32bits of raw data, for example
* Hexidecimal characters representing a 32bit value.
*
* The data must has 0xFFFFFFFF possible values, and is sortable by
* PHP sort functions using Sort_regular.
*
* @param string
* @return Mixed A sortable format with 0xFFFFFFFF possible values
*/
Public Function hash ($string);
}
/**
* Uses CRC32 to hash a value into a signed 32bit int address space.
* Under 32bit PHP (safely) overflows into negatives ints.
*
* @author Paul Annesley
* @package Flexihash
* @licence http://www.opensource.org/licenses/mit-license.php
*/
Class Flexihash_crc32hasher
Implements Flexihash_hasher
{
/* (Non-phpdoc)
* @see Flexihash_hasher::hash ()
*/
Public Function hash ($string)
{
return CRC32 ($string);
}
}
/**
* Uses CRC32 to hash a value into a 32bit binary string data address space.
*
* @author Paul Annesley
* @package Flexihash
* @licence http://www.opensource.org/licenses/mit-license.php
*/
Class Flexihash_md5hasher
Implements Flexihash_hasher
{
/* (Non-phpdoc)
* @see Flexihash_hasher::hash ()
*/
Public Function hash ($string)
{
Return substr (MD5 ($string), 0, 8); 8 hexits = 32bit
4 bytes of binary MD5 data could also be used, but
Performance seems to be the same.
}
}
/**
* An
ExceptionThrown by Flexihash.
*
* @author Paul Annesley
* @package Flexihash
* @licence http://www.opensource.org/licenses/mit-license.php
*/
Class Flexihash_
ExceptionExtends
Exception
{
}
The above describes the consistency hash-php, including the exception aspects of the content, I hope the PHP tutorial interested in a friend helpful.