ConnectionCluster.php 2.5 KB

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