RedisTrait.php 24 KB

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