KetamaPureRing.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. /**
  12. * This class implements an hashring-based distributor that uses the same
  13. * algorithm of libketama to distribute keys in a cluster using client-side
  14. * sharding.
  15. *
  16. * @author Daniele Alessandri <suppakilla@gmail.com>
  17. * @author Lorenzo Castelli <lcastelli@gmail.com>
  18. */
  19. class KetamaPureRing extends HashRing
  20. {
  21. const DEFAULT_REPLICAS = 160;
  22. /**
  23. *
  24. */
  25. public function __construct()
  26. {
  27. parent::__construct($this::DEFAULT_REPLICAS);
  28. }
  29. /**
  30. * {@inheritdoc}
  31. */
  32. protected function addNodeToRing(&$ring, $node, $totalNodes, $replicas, $weightRatio)
  33. {
  34. $nodeObject = $node['object'];
  35. $nodeHash = $this->getNodeHash($nodeObject);
  36. $replicas = (int) floor($weightRatio * $totalNodes * ($replicas / 4));
  37. for ($i = 0; $i < $replicas; $i++) {
  38. $unpackedDigest = unpack('V4', md5("$nodeHash-$i", true));
  39. foreach ($unpackedDigest as $key) {
  40. $ring[$key] = $nodeObject;
  41. }
  42. }
  43. }
  44. /**
  45. * {@inheritdoc}
  46. */
  47. public function generateKey($value)
  48. {
  49. $hash = unpack('V', md5($value, true));
  50. return $hash[1];
  51. }
  52. /**
  53. * {@inheritdoc}
  54. */
  55. protected function wrapAroundStrategy($upper, $lower, $ringKeysCount)
  56. {
  57. // Binary search for the first item in _ringkeys with a value greater
  58. // or equal to the key. If no such item exists, return the first item.
  59. return $lower < $ringKeysCount ? $lower : 0;
  60. }
  61. }