RedisTrait.php 24 KB

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