CustomDistributionStrategy.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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\Distribution\DistributionStrategyInterface;
  16. class NaiveDistributionStrategy implements DistributionStrategyInterface
  17. {
  18. private $nodes;
  19. private $nodesCount;
  20. public function __construct()
  21. {
  22. $this->nodes = array();
  23. $this->nodesCount = 0;
  24. }
  25. public function add($node, $weight = null)
  26. {
  27. $this->nodes[] = $node;
  28. $this->nodesCount++;
  29. }
  30. public function remove($node)
  31. {
  32. $this->nodes = array_filter($this->nodes, function ($n) use ($node) {
  33. return $n !== $node;
  34. });
  35. $this->nodesCount = count($this->nodes);
  36. }
  37. public function get($key)
  38. {
  39. if (0 === $count = $this->nodesCount) {
  40. throw new RuntimeException('No connections');
  41. }
  42. return $this->nodes[$count > 1 ? abs($key % $count) : 0];
  43. }
  44. public function hash($value)
  45. {
  46. return crc32($value);
  47. }
  48. }
  49. $options = array(
  50. 'cluster' => function () {
  51. $distributor = new NaiveDistributionStrategy();
  52. $cluster = new PredisCluster($distributor);
  53. return $cluster;
  54. },
  55. );
  56. $client = new Predis\Client($multiple_servers, $options);
  57. for ($i = 0; $i < 100; $i++) {
  58. $client->set("key:$i", str_pad($i, 4, '0', 0));
  59. $client->get("key:$i");
  60. }
  61. $server1 = $client->getClientFor('first')->info();
  62. $server2 = $client->getClientFor('second')->info();
  63. printf("Server '%s' has %d keys while server '%s' has %d keys.\n",
  64. 'first', $server1['db15']['keys'], 'second', $server2['db15']['keys']
  65. );