CustomDistributionStrategy.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 the Predis\Distribution\IDistributionStrategy interface.
  14. use Predis\Distribution\IDistributionStrategy;
  15. use Predis\Network\PredisCluster;
  16. class NaiveDistributionStrategy implements IDistributionStrategy
  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. $count = $this->nodesCount;
  40. if ($count === 0) {
  41. throw new RuntimeException('No connections');
  42. }
  43. return $this->nodes[$count > 1 ? abs($key % $count) : 0];
  44. }
  45. public function generateKey($value)
  46. {
  47. return crc32($value);
  48. }
  49. }
  50. $options = array(
  51. 'cluster' => function() {
  52. $distributor = new NaiveDistributionStrategy();
  53. return new PredisCluster($distributor);
  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. );