RedisTrait.php 24 KB

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