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