RedisTrait.php 25 KB

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