RedisTrait.php 19 KB

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