CustomDistributionStrategy.php 1.6 KB

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