RedisTrait.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.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 Symfony\Component\Cache\Traits;
  11. use Predis\Connection\Aggregate\ClusterInterface;
  12. use Predis\Connection\Aggregate\RedisCluster;
  13. use Predis\Connection\Aggregate\ReplicationInterface;
  14. use Predis\Response\ErrorInterface;
  15. use Predis\Response\Status;
  16. use Symfony\Component\Cache\Exception\CacheException;
  17. use Symfony\Component\Cache\Exception\InvalidArgumentException;
  18. use Symfony\Component\Cache\Marshaller\DefaultMarshaller;
  19. use Symfony\Component\Cache\Marshaller\MarshallerInterface;
  20. /**
  21. * @author Aurimas Niekis <aurimas@niekis.lt>
  22. * @author Nicolas Grekas <p@tchwork.com>
  23. *
  24. * @internal
  25. */
  26. trait RedisTrait
  27. {
  28. private static $defaultConnectionOptions = [
  29. 'class' => null,
  30. 'persistent' => 0,
  31. 'persistent_id' => null,
  32. 'timeout' => 30,
  33. 'read_timeout' => 0,
  34. 'retry_interval' => 0,
  35. 'tcp_keepalive' => 0,
  36. 'lazy' => null,
  37. 'redis_cluster' => false,
  38. 'redis_sentinel' => null,
  39. 'dbindex' => 0,
  40. 'failover' => 'none',
  41. 'ssl' => null, // see https://php.net/context.ssl
  42. ];
  43. private $redis;
  44. private $marshaller;
  45. /**
  46. * @param \Redis|\RedisArray|\RedisCluster|\Predis\ClientInterface|RedisProxy|RedisClusterProxy $redis
  47. */
  48. private function init($redis, string $namespace, int $defaultLifetime, ?MarshallerInterface $marshaller)
  49. {
  50. parent::__construct($namespace, $defaultLifetime);
  51. if (preg_match('#[^-+_.A-Za-z0-9]#', $namespace, $match)) {
  52. throw new InvalidArgumentException(sprintf('RedisAdapter namespace contains "%s" but only characters in [-+_.A-Za-z0-9] are allowed.', $match[0]));
  53. }
  54. if (!$redis instanceof \Redis && !$redis instanceof \RedisArray && !$redis instanceof \RedisCluster && !$redis instanceof \Predis\ClientInterface && !$redis instanceof RedisProxy && !$redis instanceof RedisClusterProxy) {
  55. throw new InvalidArgumentException(sprintf('"%s()" expects parameter 1 to be Redis, RedisArray, RedisCluster or Predis\ClientInterface, "%s" given.', __METHOD__, \is_object($redis) ? \get_class($redis) : \gettype($redis)));
  56. }
  57. if ($redis instanceof \Predis\ClientInterface && $redis->getOptions()->exceptions) {
  58. $options = clone $redis->getOptions();
  59. \Closure::bind(function () { $this->options['exceptions'] = false; }, $options, $options)();
  60. $redis = new $redis($redis->getConnection(), $options);
  61. }
  62. $this->redis = $redis;
  63. $this->marshaller = $marshaller ?? new DefaultMarshaller();
  64. }
  65. /**
  66. * Creates a Redis connection using a DSN configuration.
  67. *
  68. * Example DSN:
  69. * - redis://localhost
  70. * - redis://example.com:1234
  71. * - redis://secret@example.com/13
  72. * - redis:///var/run/redis.sock
  73. * - redis://secret@/var/run/redis.sock/13
  74. *
  75. * @param string $dsn
  76. * @param array $options See self::$defaultConnectionOptions
  77. *
  78. * @throws InvalidArgumentException when the DSN is invalid
  79. *
  80. * @return \Redis|\RedisCluster|RedisClusterProxy|RedisProxy|\Predis\ClientInterface According to the "class" option
  81. */
  82. public static function createConnection($dsn, array $options = [])
  83. {
  84. if (str_starts_with($dsn, 'redis:')) {
  85. $scheme = 'redis';
  86. } elseif (str_starts_with($dsn, 'rediss:')) {
  87. $scheme = 'rediss';
  88. } else {
  89. throw new InvalidArgumentException(sprintf('Invalid Redis DSN: "%s" does not start with "redis:" or "rediss".', $dsn));
  90. }
  91. if (!\extension_loaded('redis') && !class_exists(\Predis\Client::class)) {
  92. throw new CacheException(sprintf('Cannot find the "redis" extension nor the "predis/predis" package: "%s".', $dsn));
  93. }
  94. $params = preg_replace_callback('#^'.$scheme.':(//)?(?:(?:[^:@]*+:)?([^@]*+)@)?#', function ($m) use (&$auth) {
  95. if (isset($m[2])) {
  96. $auth = $m[2];
  97. if ('' === $auth) {
  98. $auth = null;
  99. }
  100. }
  101. return 'file:'.($m[1] ?? '');
  102. }, $dsn);
  103. if (false === $params = parse_url($params)) {
  104. throw new InvalidArgumentException(sprintf('Invalid Redis DSN: "%s".', $dsn));
  105. }
  106. $query = $hosts = [];
  107. $tls = 'rediss' === $scheme;
  108. $tcpScheme = $tls ? 'tls' : 'tcp';
  109. if (isset($params['query'])) {
  110. parse_str($params['query'], $query);
  111. if (isset($query['host'])) {
  112. if (!\is_array($hosts = $query['host'])) {
  113. throw new InvalidArgumentException(sprintf('Invalid Redis DSN: "%s".', $dsn));
  114. }
  115. foreach ($hosts as $host => $parameters) {
  116. if (\is_string($parameters)) {
  117. parse_str($parameters, $parameters);
  118. }
  119. if (false === $i = strrpos($host, ':')) {
  120. $hosts[$host] = ['scheme' => $tcpScheme, 'host' => $host, 'port' => 6379] + $parameters;
  121. } elseif ($port = (int) substr($host, 1 + $i)) {
  122. $hosts[$host] = ['scheme' => $tcpScheme, 'host' => substr($host, 0, $i), 'port' => $port] + $parameters;
  123. } else {
  124. $hosts[$host] = ['scheme' => 'unix', 'path' => substr($host, 0, $i)] + $parameters;
  125. }
  126. }
  127. $hosts = array_values($hosts);
  128. }
  129. }
  130. if (isset($params['host']) || isset($params['path'])) {
  131. if (!isset($params['dbindex']) && isset($params['path'])) {
  132. if (preg_match('#/(\d+)$#', $params['path'], $m)) {
  133. $params['dbindex'] = $m[1];
  134. $params['path'] = substr($params['path'], 0, -\strlen($m[0]));
  135. } elseif (isset($params['host'])) {
  136. throw new InvalidArgumentException(sprintf('Invalid Redis DSN: "%s", the "dbindex" parameter must be a number.', $dsn));
  137. }
  138. }
  139. if (isset($params['host'])) {
  140. array_unshift($hosts, ['scheme' => $tcpScheme, 'host' => $params['host'], 'port' => $params['port'] ?? 6379]);
  141. } else {
  142. array_unshift($hosts, ['scheme' => 'unix', 'path' => $params['path']]);
  143. }
  144. }
  145. if (!$hosts) {
  146. throw new InvalidArgumentException(sprintf('Invalid Redis DSN: "%s".', $dsn));
  147. }
  148. $params += $query + $options + self::$defaultConnectionOptions;
  149. if (isset($params['redis_sentinel']) && !class_exists(\Predis\Client::class)) {
  150. throw new CacheException(sprintf('Redis Sentinel support requires the "predis/predis" package: "%s".', $dsn));
  151. }
  152. if (null === $params['class'] && !isset($params['redis_sentinel']) && \extension_loaded('redis')) {
  153. $class = $params['redis_cluster'] ? \RedisCluster::class : (1 < \count($hosts) ? \RedisArray::class : \Redis::class);
  154. } else {
  155. $class = $params['class'] ?? \Predis\Client::class;
  156. }
  157. if (is_a($class, \Redis::class, true)) {
  158. $connect = $params['persistent'] || $params['persistent_id'] ? 'pconnect' : 'connect';
  159. $redis = new $class();
  160. $initializer = static function ($redis) use ($connect, $params, $dsn, $auth, $hosts, $tls) {
  161. $host = $hosts[0]['host'] ?? $hosts[0]['path'];
  162. $port = $hosts[0]['port'] ?? 0;
  163. if (isset($hosts[0]['host']) && $tls) {
  164. $host = 'tls://'.$host;
  165. }
  166. try {
  167. @$redis->{$connect}($host, $port, $params['timeout'], (string) $params['persistent_id'], $params['retry_interval'], $params['read_timeout'], ...\defined('Redis::SCAN_PREFIX') ? [['stream' => $params['ssl'] ?? null]] : []);
  168. set_error_handler(function ($type, $msg) use (&$error) { $error = $msg; });
  169. $isConnected = $redis->isConnected();
  170. restore_error_handler();
  171. if (!$isConnected) {
  172. $error = preg_match('/^Redis::p?connect\(\): (.*)/', $error, $error) ? sprintf(' (%s)', $error[1]) : '';
  173. throw new InvalidArgumentException(sprintf('Redis connection "%s" failed: ', $dsn).$error.'.');
  174. }
  175. if ((null !== $auth && !$redis->auth($auth))
  176. || ($params['dbindex'] && !$redis->select($params['dbindex']))
  177. ) {
  178. $e = preg_replace('/^ERR /', '', $redis->getLastError());
  179. throw new InvalidArgumentException(sprintf('Redis connection "%s" failed: ', $dsn).$e.'.');
  180. }
  181. if (0 < $params['tcp_keepalive'] && \defined('Redis::OPT_TCP_KEEPALIVE')) {
  182. $redis->setOption(\Redis::OPT_TCP_KEEPALIVE, $params['tcp_keepalive']);
  183. }
  184. } catch (\RedisException $e) {
  185. throw new InvalidArgumentException(sprintf('Redis connection "%s" failed: ', $dsn).$e->getMessage());
  186. }
  187. return true;
  188. };
  189. if ($params['lazy']) {
  190. $redis = new RedisProxy($redis, $initializer);
  191. } else {
  192. $initializer($redis);
  193. }
  194. } elseif (is_a($class, \RedisArray::class, true)) {
  195. foreach ($hosts as $i => $host) {
  196. switch ($host['scheme']) {
  197. case 'tcp': $hosts[$i] = $host['host'].':'.$host['port']; break;
  198. case 'tls': $hosts[$i] = 'tls://'.$host['host'].':'.$host['port']; break;
  199. default: $hosts[$i] = $host['path'];
  200. }
  201. }
  202. $params['lazy_connect'] = $params['lazy'] ?? true;
  203. $params['connect_timeout'] = $params['timeout'];
  204. try {
  205. $redis = new $class($hosts, $params);
  206. } catch (\RedisClusterException $e) {
  207. throw new InvalidArgumentException(sprintf('Redis connection "%s" failed: ', $dsn).$e->getMessage());
  208. }
  209. if (0 < $params['tcp_keepalive'] && \defined('Redis::OPT_TCP_KEEPALIVE')) {
  210. $redis->setOption(\Redis::OPT_TCP_KEEPALIVE, $params['tcp_keepalive']);
  211. }
  212. } elseif (is_a($class, \RedisCluster::class, true)) {
  213. $initializer = static function () use ($class, $params, $dsn, $hosts) {
  214. foreach ($hosts as $i => $host) {
  215. switch ($host['scheme']) {
  216. case 'tcp': $hosts[$i] = $host['host'].':'.$host['port']; break;
  217. case 'tls': $hosts[$i] = 'tls://'.$host['host'].':'.$host['port']; break;
  218. default: $hosts[$i] = $host['path'];
  219. }
  220. }
  221. try {
  222. $redis = new $class(null, $hosts, $params['timeout'], $params['read_timeout'], (bool) $params['persistent'], $params['auth'] ?? '', ...\defined('Redis::SCAN_PREFIX') ? [$params['ssl'] ?? null] : []);
  223. } catch (\RedisClusterException $e) {
  224. throw new InvalidArgumentException(sprintf('Redis connection "%s" failed: ', $dsn).$e->getMessage());
  225. }
  226. if (0 < $params['tcp_keepalive'] && \defined('Redis::OPT_TCP_KEEPALIVE')) {
  227. $redis->setOption(\Redis::OPT_TCP_KEEPALIVE, $params['tcp_keepalive']);
  228. }
  229. switch ($params['failover']) {
  230. case 'error': $redis->setOption(\RedisCluster::OPT_SLAVE_FAILOVER, \RedisCluster::FAILOVER_ERROR); break;
  231. case 'distribute': $redis->setOption(\RedisCluster::OPT_SLAVE_FAILOVER, \RedisCluster::FAILOVER_DISTRIBUTE); break;
  232. case 'slaves': $redis->setOption(\RedisCluster::OPT_SLAVE_FAILOVER, \RedisCluster::FAILOVER_DISTRIBUTE_SLAVES); break;
  233. }
  234. return $redis;
  235. };
  236. $redis = $params['lazy'] ? new RedisClusterProxy($initializer) : $initializer();
  237. } elseif (is_a($class, \Predis\ClientInterface::class, true)) {
  238. if ($params['redis_cluster']) {
  239. $params['cluster'] = 'redis';
  240. if (isset($params['redis_sentinel'])) {
  241. throw new InvalidArgumentException(sprintf('Cannot use both "redis_cluster" and "redis_sentinel" at the same time: "%s".', $dsn));
  242. }
  243. } elseif (isset($params['redis_sentinel'])) {
  244. $params['replication'] = 'sentinel';
  245. $params['service'] = $params['redis_sentinel'];
  246. }
  247. $params += ['parameters' => []];
  248. $params['parameters'] += [
  249. 'persistent' => $params['persistent'],
  250. 'timeout' => $params['timeout'],
  251. 'read_write_timeout' => $params['read_timeout'],
  252. 'tcp_nodelay' => true,
  253. ];
  254. if ($params['dbindex']) {
  255. $params['parameters']['database'] = $params['dbindex'];
  256. }
  257. if (null !== $auth) {
  258. $params['parameters']['password'] = $auth;
  259. }
  260. if (1 === \count($hosts) && !($params['redis_cluster'] || $params['redis_sentinel'])) {
  261. $hosts = $hosts[0];
  262. } elseif (\in_array($params['failover'], ['slaves', 'distribute'], true) && !isset($params['replication'])) {
  263. $params['replication'] = true;
  264. $hosts[0] += ['alias' => 'master'];
  265. }
  266. $params['exceptions'] = false;
  267. $redis = new $class($hosts, array_diff_key($params, array_diff_key(self::$defaultConnectionOptions, ['ssl' => null])));
  268. if (isset($params['redis_sentinel'])) {
  269. $redis->getConnection()->setSentinelTimeout($params['timeout']);
  270. }
  271. } elseif (class_exists($class, false)) {
  272. throw new InvalidArgumentException(sprintf('"%s" is not a subclass of "Redis", "RedisArray", "RedisCluster" nor "Predis\ClientInterface".', $class));
  273. } else {
  274. throw new InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
  275. }
  276. return $redis;
  277. }
  278. /**
  279. * {@inheritdoc}
  280. */
  281. protected function doFetch(array $ids)
  282. {
  283. if (!$ids) {
  284. return [];
  285. }
  286. $result = [];
  287. if ($this->redis instanceof \Predis\ClientInterface && $this->redis->getConnection() instanceof ClusterInterface) {
  288. $values = $this->pipeline(function () use ($ids) {
  289. foreach ($ids as $id) {
  290. yield 'get' => [$id];
  291. }
  292. });
  293. } else {
  294. $values = $this->redis->mget($ids);
  295. if (!\is_array($values) || \count($values) !== \count($ids)) {
  296. return [];
  297. }
  298. $values = array_combine($ids, $values);
  299. }
  300. foreach ($values as $id => $v) {
  301. if ($v) {
  302. $result[$id] = $this->marshaller->unmarshall($v);
  303. }
  304. }
  305. return $result;
  306. }
  307. /**
  308. * {@inheritdoc}
  309. */
  310. protected function doHave($id)
  311. {
  312. return (bool) $this->redis->exists($id);
  313. }
  314. /**
  315. * {@inheritdoc}
  316. */
  317. protected function doClear($namespace)
  318. {
  319. if ($this->redis instanceof \Predis\ClientInterface) {
  320. $prefix = $this->redis->getOptions()->prefix ? $this->redis->getOptions()->prefix->getPrefix() : '';
  321. $prefixLen = \strlen($prefix);
  322. }
  323. $cleared = true;
  324. $hosts = $this->getHosts();
  325. $host = reset($hosts);
  326. if ($host instanceof \Predis\Client && $host->getConnection() instanceof ReplicationInterface) {
  327. // Predis supports info command only on the master in replication environments
  328. $hosts = [$host->getClientFor('master')];
  329. }
  330. foreach ($hosts as $host) {
  331. if (!isset($namespace[0])) {
  332. $cleared = $host->flushDb() && $cleared;
  333. continue;
  334. }
  335. $info = $host->info('Server');
  336. $info = !$info instanceof ErrorInterface ? $info['Server'] ?? $info : ['redis_version' => '2.0'];
  337. if (!$host instanceof \Predis\ClientInterface) {
  338. $prefix = \defined('Redis::SCAN_PREFIX') && (\Redis::SCAN_PREFIX & $host->getOption(\Redis::OPT_SCAN)) ? '' : $host->getOption(\Redis::OPT_PREFIX);
  339. $prefixLen = \strlen($host->getOption(\Redis::OPT_PREFIX) ?? '');
  340. }
  341. $pattern = $prefix.$namespace.'*';
  342. if (!version_compare($info['redis_version'], '2.8', '>=')) {
  343. // As documented in Redis documentation (http://redis.io/commands/keys) using KEYS
  344. // can hang your server when it is executed against large databases (millions of items).
  345. // Whenever you hit this scale, you should really consider upgrading to Redis 2.8 or above.
  346. $args = $this->redis instanceof \Predis\ClientInterface ? [0, $pattern] : [[$pattern], 0];
  347. $cleared = $host->eval("local keys=redis.call('KEYS',ARGV[1]) for i=1,#keys,5000 do redis.call('DEL',unpack(keys,i,math.min(i+4999,#keys))) end return 1", $args[0], $args[1]) && $cleared;
  348. continue;
  349. }
  350. $cursor = null;
  351. do {
  352. $keys = $host instanceof \Predis\ClientInterface ? $host->scan($cursor, 'MATCH', $pattern, 'COUNT', 1000) : $host->scan($cursor, $pattern, 1000);
  353. if (isset($keys[1]) && \is_array($keys[1])) {
  354. $cursor = $keys[0];
  355. $keys = $keys[1];
  356. }
  357. if ($keys) {
  358. if ($prefixLen) {
  359. foreach ($keys as $i => $key) {
  360. $keys[$i] = substr($key, $prefixLen);
  361. }
  362. }
  363. $this->doDelete($keys);
  364. }
  365. } while ($cursor = (int) $cursor);
  366. }
  367. return $cleared;
  368. }
  369. /**
  370. * {@inheritdoc}
  371. */
  372. protected function doDelete(array $ids)
  373. {
  374. if (!$ids) {
  375. return true;
  376. }
  377. if ($this->redis instanceof \Predis\ClientInterface && $this->redis->getConnection() instanceof ClusterInterface) {
  378. $this->pipeline(function () use ($ids) {
  379. foreach ($ids as $id) {
  380. yield 'del' => [$id];
  381. }
  382. })->rewind();
  383. } else {
  384. $this->redis->del($ids);
  385. }
  386. return true;
  387. }
  388. /**
  389. * {@inheritdoc}
  390. */
  391. protected function doSave(array $values, int $lifetime)
  392. {
  393. if (!$values = $this->marshaller->marshall($values, $failed)) {
  394. return $failed;
  395. }
  396. $results = $this->pipeline(function () use ($values, $lifetime) {
  397. foreach ($values as $id => $value) {
  398. if (0 >= $lifetime) {
  399. yield 'set' => [$id, $value];
  400. } else {
  401. yield 'setEx' => [$id, $lifetime, $value];
  402. }
  403. }
  404. });
  405. foreach ($results as $id => $result) {
  406. if (true !== $result && (!$result instanceof Status || Status::get('OK') !== $result)) {
  407. $failed[] = $id;
  408. }
  409. }
  410. return $failed;
  411. }
  412. private function pipeline(\Closure $generator, $redis = null): \Generator
  413. {
  414. $ids = [];
  415. $redis = $redis ?? $this->redis;
  416. if ($redis instanceof RedisClusterProxy || $redis instanceof \RedisCluster || ($redis instanceof \Predis\ClientInterface && $redis->getConnection() instanceof RedisCluster)) {
  417. // phpredis & predis don't support pipelining with RedisCluster
  418. // see https://github.com/phpredis/phpredis/blob/develop/cluster.markdown#pipelining
  419. // see https://github.com/nrk/predis/issues/267#issuecomment-123781423
  420. $results = [];
  421. foreach ($generator() as $command => $args) {
  422. $results[] = $redis->{$command}(...$args);
  423. $ids[] = 'eval' === $command ? ($redis instanceof \Predis\ClientInterface ? $args[2] : $args[1][0]) : $args[0];
  424. }
  425. } elseif ($redis instanceof \Predis\ClientInterface) {
  426. $results = $redis->pipeline(static function ($redis) use ($generator, &$ids) {
  427. foreach ($generator() as $command => $args) {
  428. $redis->{$command}(...$args);
  429. $ids[] = 'eval' === $command ? $args[2] : $args[0];
  430. }
  431. });
  432. } elseif ($redis instanceof \RedisArray) {
  433. $connections = $results = $ids = [];
  434. foreach ($generator() as $command => $args) {
  435. $id = 'eval' === $command ? $args[1][0] : $args[0];
  436. if (!isset($connections[$h = $redis->_target($id)])) {
  437. $connections[$h] = [$redis->_instance($h), -1];
  438. $connections[$h][0]->multi(\Redis::PIPELINE);
  439. }
  440. $connections[$h][0]->{$command}(...$args);
  441. $results[] = [$h, ++$connections[$h][1]];
  442. $ids[] = $id;
  443. }
  444. foreach ($connections as $h => $c) {
  445. $connections[$h] = $c[0]->exec();
  446. }
  447. foreach ($results as $k => [$h, $c]) {
  448. $results[$k] = $connections[$h][$c];
  449. }
  450. } else {
  451. $redis->multi(\Redis::PIPELINE);
  452. foreach ($generator() as $command => $args) {
  453. $redis->{$command}(...$args);
  454. $ids[] = 'eval' === $command ? $args[1][0] : $args[0];
  455. }
  456. $results = $redis->exec();
  457. }
  458. if (!$redis instanceof \Predis\ClientInterface && 'eval' === $command && $redis->getLastError()) {
  459. $e = new \RedisException($redis->getLastError());
  460. $results = array_map(function ($v) use ($e) { return false === $v ? $e : $v; }, $results);
  461. }
  462. foreach ($ids as $k => $id) {
  463. yield $id => $results[$k];
  464. }
  465. }
  466. private function getHosts(): array
  467. {
  468. $hosts = [$this->redis];
  469. if ($this->redis instanceof \Predis\ClientInterface) {
  470. $connection = $this->redis->getConnection();
  471. if ($connection instanceof ClusterInterface && $connection instanceof \Traversable) {
  472. $hosts = [];
  473. foreach ($connection as $c) {
  474. $hosts[] = new \Predis\Client($c);
  475. }
  476. }
  477. } elseif ($this->redis instanceof \RedisArray) {
  478. $hosts = [];
  479. foreach ($this->redis->_hosts() as $host) {
  480. $hosts[] = $this->redis->_instance($host);
  481. }
  482. } elseif ($this->redis instanceof RedisClusterProxy || $this->redis instanceof \RedisCluster) {
  483. $hosts = [];
  484. foreach ($this->redis->_masters() as $host) {
  485. $hosts[] = new RedisClusterNodeProxy($host, $this->redis);
  486. }
  487. }
  488. return $hosts;
  489. }
  490. }