CustomDistributionStrategy.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. require '../lib/Predis.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\IDistributionAlgorithm 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. $servers = array(
  35. 'redis://127.0.0.1:6379?alias=first',
  36. 'redis://127.0.0.1:6380?alias=second',
  37. );
  38. $options = array(
  39. 'key_distribution' => new NaiveDistributionStrategy(),
  40. );
  41. $redis = new Predis\Client($servers, $options);
  42. for ($i = 0; $i < 100; $i++) {
  43. $redis->set("key:$i", str_pad($i, 4, '0', 0));
  44. $redis->get("key:$i");
  45. }
  46. $server1 = $redis->getClientFor('first')->info();
  47. $server2 = $redis->getClientFor('second')->info();
  48. printf("Server '%s' has %d keys while server '%s' has %d keys.\n",
  49. 'first', $server1['db0']['keys'], 'second', $server2['db0']['keys']
  50. );
  51. ?>