CustomDistributionStrategy.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. {
  10. private $_nodes;
  11. private $_nodesCount;
  12. public function __constructor()
  13. {
  14. $this->_nodes = array();
  15. $this->_nodesCount = 0;
  16. }
  17. public function add($node, $weight = null)
  18. {
  19. $this->_nodes[] = $node;
  20. $this->_nodesCount++;
  21. }
  22. public function remove($node)
  23. {
  24. $this->_nodes = array_filter($this->_nodes, function($n) use($node) {
  25. return $n !== $node;
  26. });
  27. $this->_nodesCount = count($this->_nodes);
  28. }
  29. public function get($key)
  30. {
  31. $count = $this->_nodesCount;
  32. if ($count === 0) {
  33. throw new RuntimeException('No connections');
  34. }
  35. return $this->_nodes[$count > 1 ? abs(crc32($key) % $count) : 0];
  36. }
  37. public function generateKey($value)
  38. {
  39. return crc32($value);
  40. }
  41. }
  42. $options = array(
  43. 'cluster' => function() {
  44. return new PredisCluster(new NaiveDistributionStrategy());
  45. },
  46. );
  47. $redis = new Predis\Client($multiple_servers, $options);
  48. for ($i = 0; $i < 100; $i++) {
  49. $redis->set("key:$i", str_pad($i, 4, '0', 0));
  50. $redis->get("key:$i");
  51. }
  52. $server1 = $redis->getClientFor('first')->info();
  53. $server2 = $redis->getClientFor('second')->info();
  54. printf("Server '%s' has %d keys while server '%s' has %d keys.\n",
  55. 'first', $server1['db15']['keys'], 'second', $server2['db15']['keys']
  56. );