KetamaPureRing.php 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. <?php
  2. namespace Predis\Distribution;
  3. class KetamaPureRing extends HashRing
  4. {
  5. const DEFAULT_REPLICAS = 160;
  6. public function __construct()
  7. {
  8. parent::__construct($this::DEFAULT_REPLICAS);
  9. }
  10. protected function addNodeToRing(&$ring, $node, $totalNodes, $replicas, $weightRatio)
  11. {
  12. $nodeObject = $node['object'];
  13. $nodeHash = $this->getNodeHash($nodeObject);
  14. $replicas = (int) floor($weightRatio * $totalNodes * ($replicas / 4));
  15. for ($i = 0; $i < $replicas; $i++) {
  16. $unpackedDigest = unpack('V4', md5("$nodeHash-$i", true));
  17. foreach ($unpackedDigest as $key) {
  18. $ring[$key] = $nodeObject;
  19. }
  20. }
  21. }
  22. public function generateKey($value)
  23. {
  24. $hash = unpack('V', md5($value, true));
  25. return $hash[1];
  26. }
  27. protected function wrapAroundStrategy($upper, $lower, $ringKeysCount)
  28. {
  29. // Binary search for the first item in _ringkeys with a value greater
  30. // or equal to the key. If no such item exists, return the first item.
  31. return $lower < $ringKeysCount ? $lower : 0;
  32. }
  33. }