RedisCluster.php 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. <?php
  2. /*
  3. * This file is part of the Predis package.
  4. *
  5. * (c) Daniele Alessandri <suppakilla@gmail.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Predis\Connection;
  11. use Predis\ResponseErrorInterface;
  12. use Predis\ConnectionFactoryInterface;
  13. use Predis\Command\CommandInterface;
  14. use Predis\ClientException;
  15. use Predis\NotSupportedException;
  16. use Predis\Distribution\CRC16HashGenerator;
  17. /**
  18. * Abstraction for Redis cluster (Redis v3.0).
  19. *
  20. * @author Daniele Alessandri <suppakilla@gmail.com>
  21. */
  22. class RedisCluster implements ClusterConnectionInterface, \IteratorAggregate, \Countable
  23. {
  24. private $pool;
  25. private $slots;
  26. private $connections;
  27. private $hashgenerator;
  28. /**
  29. * @param ConnectionFactoryInterface $connections Connection factory object.
  30. */
  31. public function __construct(ConnectionFactoryInterface $connections = null)
  32. {
  33. $this->pool = array();
  34. $this->slots = array();
  35. $this->connections = $connections;
  36. $this->hashgenerator = new CRC16HashGenerator();
  37. }
  38. /**
  39. * {@inheritdoc}
  40. */
  41. public function isConnected()
  42. {
  43. foreach ($this->pool as $connection) {
  44. if ($connection->isConnected()) {
  45. return true;
  46. }
  47. }
  48. return false;
  49. }
  50. /**
  51. * {@inheritdoc}
  52. */
  53. public function connect()
  54. {
  55. foreach ($this->pool as $connection) {
  56. $connection->connect();
  57. }
  58. }
  59. /**
  60. * {@inheritdoc}
  61. */
  62. public function disconnect()
  63. {
  64. foreach ($this->pool as $connection) {
  65. $connection->disconnect();
  66. }
  67. }
  68. /**
  69. * {@inheritdoc}
  70. */
  71. public function add(SingleConnectionInterface $connection)
  72. {
  73. $parameters = $connection->getParameters();
  74. $this->pool["{$parameters->host}:{$parameters->port}"] = $connection;
  75. }
  76. /**
  77. * {@inheritdoc}
  78. */
  79. public function remove(SingleConnectionInterface $connection)
  80. {
  81. if (($id = array_search($connection, $this->pool, true)) !== false) {
  82. unset($this->pool[$id]);
  83. return true;
  84. }
  85. return false;
  86. }
  87. /**
  88. * Removes a connection instance using its alias or index.
  89. *
  90. * @param string $connectionId Alias or index of a connection.
  91. * @return Boolean Returns true if the connection was in the pool.
  92. */
  93. public function removeById($connectionId)
  94. {
  95. if (isset($this->pool[$connectionId])) {
  96. unset($this->pool[$connectionId]);
  97. return true;
  98. }
  99. return false;
  100. }
  101. /**
  102. * {@inheritdoc}
  103. */
  104. public function getConnection(CommandInterface $command)
  105. {
  106. if ($hash = $command->getHash() === null) {
  107. $hash = $this->hashgenerator->hash($command->getArgument(0));
  108. if (!isset($hash)) {
  109. throw new NotSupportedException("Cannot send {$command->getId()} commands to redis-cluster");
  110. }
  111. }
  112. $slot = $hash & 0x0FFF;
  113. if (isset($this->slots[$slot])) {
  114. return $this->slots[$slot];
  115. }
  116. $connection = $this->pool[array_rand($this->pool)];
  117. $this->slots[$slot] = $connection;
  118. return $connection;
  119. }
  120. /**
  121. * {@inheritdoc}
  122. */
  123. public function getConnectionById($id = null)
  124. {
  125. if (!isset($id)) {
  126. throw new \InvalidArgumentException("A valid connection ID must be specified");
  127. }
  128. return isset($this->pool[$id]) ? $this->pool[$id] : null;
  129. }
  130. /**
  131. * Handles -MOVED or -ASK replies by re-executing the command on the server
  132. * specified by the Redis reply.
  133. *
  134. * @param CommandInterface $command Command that generated the -MOVE or -ASK reply.
  135. * @param string $request Type of request (either 'MOVED' or 'ASK').
  136. * @param string $details Parameters of the MOVED/ASK request.
  137. * @return mixed
  138. */
  139. protected function onMoveRequest(CommandInterface $command, $request, $details)
  140. {
  141. list($slot, $host) = explode(' ', $details, 2);
  142. $connection = $this->getConnectionById($host);
  143. if (!isset($connection)) {
  144. $parameters = array('host' => null, 'port' => null);
  145. list($parameters['host'], $parameters['port']) = explode(':', $host, 2);
  146. $connection = $this->connections->create($parameters);
  147. }
  148. switch ($request) {
  149. case 'MOVED':
  150. $this->add($connection);
  151. $this->slots[$slot] = $connection;
  152. return $this->executeCommand($command);
  153. case 'ASK':
  154. return $connection->executeCommand($command);
  155. default:
  156. throw new ClientException("Unexpected request type for a move request: $request");
  157. }
  158. }
  159. /**
  160. * {@inheritdoc}
  161. */
  162. public function count()
  163. {
  164. return count($this->pool);
  165. }
  166. /**
  167. * {@inheritdoc}
  168. */
  169. public function getIterator()
  170. {
  171. return new \ArrayIterator($this->pool);
  172. }
  173. /**
  174. * Handles -ERR replies from Redis.
  175. *
  176. * @param CommandInterface $command Command that generated the -ERR reply.
  177. * @param ResponseErrorInterface $error Redis error reply object.
  178. * @return mixed
  179. */
  180. protected function handleServerError(CommandInterface $command, ResponseErrorInterface $error)
  181. {
  182. list($type, $details) = explode(' ', $error->getMessage(), 2);
  183. switch ($type) {
  184. case 'MOVED':
  185. case 'ASK':
  186. return $this->onMoveRequest($command, $type, $details);
  187. default:
  188. return $error;
  189. }
  190. }
  191. /**
  192. * {@inheritdoc}
  193. */
  194. public function writeCommand(CommandInterface $command)
  195. {
  196. $this->getConnection($command)->writeCommand($command);
  197. }
  198. /**
  199. * {@inheritdoc}
  200. */
  201. public function readResponse(CommandInterface $command)
  202. {
  203. return $this->getConnection($command)->readResponse($command);
  204. }
  205. /**
  206. * {@inheritdoc}
  207. */
  208. public function executeCommand(CommandInterface $command)
  209. {
  210. $connection = $this->getConnection($command);
  211. $reply = $connection->executeCommand($command);
  212. if ($reply instanceof ResponseErrorInterface) {
  213. return $this->handleServerError($command, $reply);
  214. }
  215. return $reply;
  216. }
  217. }