CustomDistributionStrategy.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. private static function array_remove($array, $value) {
  18. $newArray = array();
  19. foreach ($array as $k => $v) {
  20. if ($v !== $value) {
  21. $newArray[] = $v;
  22. }
  23. }
  24. return $newArray;
  25. }
  26. public function remove($node) {
  27. $this->_nodes = self::array_remove($this->_nodes, $node);
  28. $this->_nodesCount = count($this->_nodes);
  29. }
  30. public function get($key) {
  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. return crc32($value);
  39. }
  40. }
  41. $options = array(
  42. 'key_distribution' => new NaiveDistributionStrategy(),
  43. );
  44. $redis = new Predis_Client($multiple_servers, $options);
  45. for ($i = 0; $i < 100; $i++) {
  46. $redis->set("key:$i", str_pad($i, 4, '0', 0));
  47. $redis->get("key:$i");
  48. }
  49. $server1 = $redis->getClientFor('first')->info();
  50. $server2 = $redis->getClientFor('second')->info();
  51. printf("Server '%s' has %d keys while server '%s' has %d keys.\n",
  52. 'first', $server1['db15']['keys'], 'second', $server2['db15']['keys']
  53. );
  54. ?>