CustomDistributionStrategy.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. require 'SharedConfigurations.php';
  11. // Developers can customize the distribution strategy used by the client
  12. // to distribute keys among a cluster of servers simply by creating a class
  13. // that implements Predis\Distribution\DistributionStrategyInterface.
  14. use Predis\Connection\PredisCluster;
  15. use Predis\Cluster\Distribution\DistributionStrategyInterface;
  16. use Predis\Cluster\Hash\HashGeneratorInterface;
  17. class NaiveDistributionStrategy implements DistributionStrategyInterface, HashGeneratorInterface
  18. {
  19. private $nodes;
  20. private $nodesCount;
  21. public function __construct()
  22. {
  23. $this->nodes = array();
  24. $this->nodesCount = 0;
  25. }
  26. public function add($node, $weight = null)
  27. {
  28. $this->nodes[] = $node;
  29. $this->nodesCount++;
  30. }
  31. public function remove($node)
  32. {
  33. $this->nodes = array_filter($this->nodes, function ($n) use ($node) {
  34. return $n !== $node;
  35. });
  36. $this->nodesCount = count($this->nodes);
  37. }
  38. public function get($key)
  39. {
  40. if (0 === $count = $this->nodesCount) {
  41. throw new RuntimeException('No connections');
  42. }
  43. return $this->nodes[$count > 1 ? abs($key % $count) : 0];
  44. }
  45. public function hash($value)
  46. {
  47. return crc32($value);
  48. }
  49. public function getHashGenerator()
  50. {
  51. return $this;
  52. }
  53. }
  54. $options = array(
  55. 'cluster' => function () {
  56. $distributor = new NaiveDistributionStrategy();
  57. $cluster = new PredisCluster($distributor);
  58. return $cluster;
  59. },
  60. );
  61. $client = new Predis\Client($multiple_servers, $options);
  62. for ($i = 0; $i < 100; $i++) {
  63. $client->set("key:$i", str_pad($i, 4, '0', 0));
  64. $client->get("key:$i");
  65. }
  66. $server1 = $client->getClientFor('first')->info();
  67. $server2 = $client->getClientFor('second')->info();
  68. printf("Server '%s' has %d keys while server '%s' has %d keys.\n",
  69. 'first', $server1['db15']['keys'], 'second', $server2['db15']['keys']
  70. );