CustomDistributionStrategy.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. require 'SharedConfigurations.php';
  3. // Developers can customize the distribution strategy used by the client
  4. // to distribute keys among a cluster of servers simply by creating a class
  5. // that implements the Predis\Distribution\IDistributionStrategy interface.
  6. use Predis\Distribution\IDistributionStrategy;
  7. use Predis\Network\PredisCluster;
  8. class NaiveDistributionStrategy implements IDistributionStrategy {
  9. private $_nodes, $_nodesCount;
  10. public function __constructor() {
  11. $this->_nodes = array();
  12. $this->_nodesCount = 0;
  13. }
  14. public function add($node, $weight = null) {
  15. $this->_nodes[] = $node;
  16. $this->_nodesCount++;
  17. }
  18. public function remove($node) {
  19. $this->_nodes = array_filter($this->_nodes, function($n) use($node) {
  20. return $n !== $node;
  21. });
  22. $this->_nodesCount = count($this->_nodes);
  23. }
  24. public function get($key) {
  25. $count = $this->_nodesCount;
  26. if ($count === 0) {
  27. throw new RuntimeException('No connections');
  28. }
  29. return $this->_nodes[$count > 1 ? abs(crc32($key) % $count) : 0];
  30. }
  31. public function generateKey($value) {
  32. return crc32($value);
  33. }
  34. }
  35. $options = array(
  36. 'cluster' => function() {
  37. return new PredisCluster(new NaiveDistributionStrategy());
  38. },
  39. );
  40. $redis = new Predis\Client($multiple_servers, $options);
  41. for ($i = 0; $i < 100; $i++) {
  42. $redis->set("key:$i", str_pad($i, 4, '0', 0));
  43. $redis->get("key:$i");
  44. }
  45. $server1 = $redis->getClientFor('first')->info();
  46. $server2 = $redis->getClientFor('second')->info();
  47. printf("Server '%s' has %d keys while server '%s' has %d keys.\n",
  48. 'first', $server1['db15']['keys'], 'second', $server2['db15']['keys']
  49. );