A complete example of a consistent hash algorithm implemented by PHP, a consistent hashing algorithm _php tutorial

Source: Internet
Author: User
Tags crc32

A complete example of a consistent hash algorithm implemented by PHP, a consistent hashing algorithm


In this paper, we describe the consistent hashing algorithm implemented by PHP. Share to everyone for your reference, as follows:

<?php/** * Flexihash-a Simple consistent hashing implementation for PHP. * * The MIT License * * Copyright (c) Paul Annesley * * Permission is hereby granted, free of charge, to any Perso n Obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the software Witho UT restriction, including without limitation the rights * To use, copy, modify, merge, publish, distribute, sublicense, an d/or Sell * Copies of the software, and to permit persons to whom the software are * furnished to doing so, subject to the FOL lowing Conditions: * * The above copyright notice and this permission notice shall is included in * all copies or Substan Tial portions of the software. * * The software is provided ' as is ', without WARRANTY of any KIND, EXPRESS OR * implied, including and not LIMITED to TH E warranties of merchantability, * FITNESS for A particular PURPOSE and noninfringement. In NO EVENT shall the * AUTHORS OR COPYRIGHT Holders is liable for any CLAIM, damages or other * liability, WHETHER in a ACTION of contract, TORT OR OTHERWISE, arising from, * off of OR in CO Nnection with the software or the same or other dealings in * the software. * * @author Paul Annesley * @link http://paul.annesley.cc/* @copyright Paul Annesley, @comment by Myz (Http://blo G.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 Flexi   hash{/** * 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 hash method used: 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 access according to location */private $_positiontotarget = Array ();   /** * Internal Map of targets to lists of positions, the target is hashed to.   * @var Array {target = [position, position, ...], ...}  * @comment node corresponding location, for deleting node */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 T   Arget to.  * @comment constructor, determine the hash method to use and the number of desired nodes, the more the number of virtual nodes, the more evenly distributed, but the program's distributed operation is slower */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 and distribute the 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 exis    ts. ");}    $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 Flexiha    Sh_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 TA Rgets * @comment Find the node of the current resource, * The node is empty, return null, only one node returns the node, * hash the current resource, sort all the positions, and find the location of the current resource in the ordered position column * when When all is not found, the location of the resource is determined 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->_positiontot    Arget));    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) {//STA RT 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 =&gt ;      $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 Targe TS) 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 F   lexihash_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 32bi   T 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 Flexi Hash_crc32hasher Implements flexihash_hasher{/* (non-phpdoc) * @see flexihash_hasher::hash () */Public Function ha  SH ($string) {return CRC32 ($string); }}/** * Uses CRC32 to hashes 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 Flexi Hash_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 beUsed, but//performance seems to be the same. }}/** * An exception thrown by Flexihash. * * @author Paul Annesley * @package Flexihash * @licence http://www.opensource.org/licenses/mit-license.php */class Flexi Hash_exception extends exception{}

I hope this article is helpful to you in PHP programming.

http://www.bkjia.com/PHPjc/1071395.html www.bkjia.com true http://www.bkjia.com/PHPjc/1071395.html techarticle A complete example of a consistent hash algorithm implemented by PHP, a consistent hashing algorithm This paper describes the consistent hashing algorithm implemented by PHP. Share to everyone for your reference, as follows: php/ ...

  • 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.