KetamaPureRing.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php
  2. /*
  3. * This file is part of the Predis package.
  4. *
  5. * (c) Daniele Alessandri <suppakilla@gmail.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Predis\Distribution;
  11. class KetamaPureRing extends HashRing
  12. {
  13. const DEFAULT_REPLICAS = 160;
  14. public function __construct()
  15. {
  16. parent::__construct($this::DEFAULT_REPLICAS);
  17. }
  18. protected function addNodeToRing(&$ring, $node, $totalNodes, $replicas, $weightRatio)
  19. {
  20. $nodeObject = $node['object'];
  21. $nodeHash = $this->getNodeHash($nodeObject);
  22. $replicas = (int) floor($weightRatio * $totalNodes * ($replicas / 4));
  23. for ($i = 0; $i < $replicas; $i++) {
  24. $unpackedDigest = unpack('V4', md5("$nodeHash-$i", true));
  25. foreach ($unpackedDigest as $key) {
  26. $ring[$key] = $nodeObject;
  27. }
  28. }
  29. }
  30. public function generateKey($value)
  31. {
  32. $hash = unpack('V', md5($value, true));
  33. return $hash[1];
  34. }
  35. protected function wrapAroundStrategy($upper, $lower, $ringKeysCount)
  36. {
  37. // Binary search for the first item in _ringkeys with a value greater
  38. // or equal to the key. If no such item exists, return the first item.
  39. return $lower < $ringKeysCount ? $lower : 0;
  40. }
  41. }