PredisStrategy.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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\Cluster;
  11. use Predis\Cluster\Distributor\DistributorInterface;
  12. use Predis\Cluster\Distributor\HashRing;
  13. /**
  14. * Default cluster strategy used by Predis to handle client-side sharding.
  15. *
  16. * @author Daniele Alessandri <suppakilla@gmail.com>
  17. */
  18. class PredisStrategy extends ClusterStrategy
  19. {
  20. protected $distributor;
  21. /**
  22. * @param DistributorInterface $distributor Optional distributor instance.
  23. */
  24. public function __construct(DistributorInterface $distributor = null)
  25. {
  26. parent::__construct();
  27. $this->distributor = $distributor ?: new HashRing();
  28. }
  29. /**
  30. * {@inheritdoc}
  31. */
  32. public function getSlotByKey($key)
  33. {
  34. $key = $this->extractKeyTag($key);
  35. $hash = $this->distributor->hash($key);
  36. $slot = $this->distributor->getSlot($hash);
  37. return $slot;
  38. }
  39. /**
  40. * {@inheritdoc}
  41. */
  42. protected function checkSameSlotForKeys(array $keys)
  43. {
  44. if (!$count = count($keys)) {
  45. return false;
  46. }
  47. $currentKey = $this->extractKeyTag($keys[0]);
  48. for ($i = 1; $i < $count; $i++) {
  49. $nextKey = $this->extractKeyTag($keys[$i]);
  50. if ($currentKey !== $nextKey) {
  51. return false;
  52. }
  53. $currentKey = $nextKey;
  54. }
  55. return true;
  56. }
  57. /**
  58. * {@inheritdoc}
  59. */
  60. public function getDistributor()
  61. {
  62. return $this->distributor;
  63. }
  64. }