PredisCluster.php 2.5 KB

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