PredisCluster.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace Predis\Network;
  3. use Predis\Helpers;
  4. use Predis\ClientException;
  5. use Predis\Commands\ICommand;
  6. use Predis\Distribution\IDistributionStrategy;
  7. use Predis\Distribution\HashRing;
  8. class PredisCluster implements IConnectionCluster, \IteratorAggregate {
  9. private $_pool;
  10. private $_distributor;
  11. public function __construct(IDistributionStrategy $distributor = null) {
  12. $this->_pool = array();
  13. $this->_distributor = $distributor ?: new HashRing();
  14. }
  15. public function isConnected() {
  16. foreach ($this->_pool as $connection) {
  17. if ($connection->isConnected()) {
  18. return true;
  19. }
  20. }
  21. return false;
  22. }
  23. public function connect() {
  24. foreach ($this->_pool as $connection) {
  25. $connection->connect();
  26. }
  27. }
  28. public function disconnect() {
  29. foreach ($this->_pool as $connection) {
  30. $connection->disconnect();
  31. }
  32. }
  33. public function add(IConnectionSingle $connection) {
  34. $parameters = $connection->getParameters();
  35. if (isset($parameters->alias)) {
  36. $this->_pool[$parameters->alias] = $connection;
  37. }
  38. else {
  39. $this->_pool[] = $connection;
  40. }
  41. $this->_distributor->add($connection, $parameters->weight);
  42. }
  43. public function getConnection(ICommand $command) {
  44. $cmdHash = $command->getHash($this->_distributor);
  45. if (isset($cmdHash)) {
  46. return $this->_distributor->get($cmdHash);
  47. }
  48. throw new ClientException(
  49. sprintf("Cannot send '%s' commands to a cluster of connections", $command->getId())
  50. );
  51. }
  52. public function getConnectionById($id = null) {
  53. $alias = $id ?: 0;
  54. return isset($this->_pool[$alias]) ? $this->_pool[$alias] : null;
  55. }
  56. public function getConnectionByKey($key) {
  57. $hashablePart = Helpers::getKeyHashablePart($key);
  58. $keyHash = $this->_distributor->generateKey($hashablePart);
  59. return $this->_distributor->get($keyHash);
  60. }
  61. public function getIterator() {
  62. return new \ArrayIterator($this->_pool);
  63. }
  64. public function writeCommand(ICommand $command) {
  65. $this->getConnection($command)->writeCommand($command);
  66. }
  67. public function readResponse(ICommand $command) {
  68. return $this->getConnection($command)->readResponse($command);
  69. }
  70. public function executeCommand(ICommand $command) {
  71. return $this->getConnection($command)->executeCommand($command);
  72. }
  73. }