RedisTrait.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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\PredisCluster;
  13. use Predis\Connection\Aggregate\RedisCluster;
  14. use Predis\Connection\Factory;
  15. use Predis\Response\Status;
  16. use Symfony\Component\Cache\Exception\CacheException;
  17. use Symfony\Component\Cache\Exception\InvalidArgumentException;
  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. 'lazy' => false,
  34. ];
  35. private $redis;
  36. /**
  37. * @param \Redis|\RedisArray|\RedisCluster|\Predis\Client $redisClient
  38. */
  39. private function init($redisClient, $namespace = '', $defaultLifetime = 0)
  40. {
  41. parent::__construct($namespace, $defaultLifetime);
  42. if (preg_match('#[^-+_.A-Za-z0-9]#', $namespace, $match)) {
  43. throw new InvalidArgumentException(sprintf('RedisAdapter namespace contains "%s" but only characters in [-+_.A-Za-z0-9] are allowed.', $match[0]));
  44. }
  45. if ($redisClient instanceof \RedisCluster) {
  46. $this->enableVersioning();
  47. } elseif (!$redisClient instanceof \Redis && !$redisClient instanceof \RedisArray && !$redisClient instanceof \Predis\Client && !$redisClient instanceof RedisProxy) {
  48. throw new InvalidArgumentException(sprintf('%s() expects parameter 1 to be Redis, RedisArray, RedisCluster or Predis\Client, %s given', __METHOD__, \is_object($redisClient) ? \get_class($redisClient) : \gettype($redisClient)));
  49. }
  50. $this->redis = $redisClient;
  51. }
  52. /**
  53. * Creates a Redis connection using a DSN configuration.
  54. *
  55. * Example DSN:
  56. * - redis://localhost
  57. * - redis://example.com:1234
  58. * - redis://secret@example.com/13
  59. * - redis:///var/run/redis.sock
  60. * - redis://secret@/var/run/redis.sock/13
  61. *
  62. * @param string $dsn
  63. * @param array $options See self::$defaultConnectionOptions
  64. *
  65. * @throws InvalidArgumentException when the DSN is invalid
  66. *
  67. * @return \Redis|\Predis\Client According to the "class" option
  68. */
  69. public static function createConnection($dsn, array $options = [])
  70. {
  71. if (0 !== strpos($dsn, 'redis://')) {
  72. throw new InvalidArgumentException(sprintf('Invalid Redis DSN: %s does not start with "redis://"', $dsn));
  73. }
  74. $params = preg_replace_callback('#^redis://(?:(?:[^:@]*+:)?([^@]*+)@)?#', function ($m) use (&$auth) {
  75. if (isset($m[1])) {
  76. $auth = $m[1];
  77. }
  78. return 'file://';
  79. }, $dsn);
  80. if (false === $params = parse_url($params)) {
  81. throw new InvalidArgumentException(sprintf('Invalid Redis DSN: %s', $dsn));
  82. }
  83. if (!isset($params['host']) && !isset($params['path'])) {
  84. throw new InvalidArgumentException(sprintf('Invalid Redis DSN: %s', $dsn));
  85. }
  86. if (isset($params['path']) && preg_match('#/(\d+)$#', $params['path'], $m)) {
  87. $params['dbindex'] = $m[1];
  88. $params['path'] = substr($params['path'], 0, -\strlen($m[0]));
  89. }
  90. if (isset($params['host'])) {
  91. $scheme = 'tcp';
  92. } else {
  93. $scheme = 'unix';
  94. }
  95. $params += [
  96. 'host' => isset($params['host']) ? $params['host'] : $params['path'],
  97. 'port' => isset($params['host']) ? 6379 : null,
  98. 'dbindex' => 0,
  99. ];
  100. if (isset($params['query'])) {
  101. parse_str($params['query'], $query);
  102. $params += $query;
  103. }
  104. $params += $options + self::$defaultConnectionOptions;
  105. if (null === $params['class'] && !\extension_loaded('redis') && !class_exists(\Predis\Client::class)) {
  106. throw new CacheException(sprintf('Cannot find the "redis" extension, and "predis/predis" is not installed: %s', $dsn));
  107. }
  108. $class = null === $params['class'] ? (\extension_loaded('redis') ? \Redis::class : \Predis\Client::class) : $params['class'];
  109. if (is_a($class, \Redis::class, true)) {
  110. $connect = $params['persistent'] || $params['persistent_id'] ? 'pconnect' : 'connect';
  111. $redis = new $class();
  112. $initializer = function ($redis) use ($connect, $params, $dsn, $auth) {
  113. try {
  114. @$redis->{$connect}($params['host'], $params['port'], $params['timeout'], $params['persistent_id'], $params['retry_interval']);
  115. } catch (\RedisException $e) {
  116. throw new InvalidArgumentException(sprintf('Redis connection failed (%s): %s', $e->getMessage(), $dsn));
  117. }
  118. set_error_handler(function ($type, $msg) use (&$error) { $error = $msg; });
  119. $isConnected = $redis->isConnected();
  120. restore_error_handler();
  121. if (!$isConnected) {
  122. $error = preg_match('/^Redis::p?connect\(\): (.*)/', $error, $error) ? sprintf(' (%s)', $error[1]) : '';
  123. throw new InvalidArgumentException(sprintf('Redis connection failed%s: %s', $error, $dsn));
  124. }
  125. if ((null !== $auth && !$redis->auth($auth))
  126. || ($params['dbindex'] && !$redis->select($params['dbindex']))
  127. || ($params['read_timeout'] && !$redis->setOption(\Redis::OPT_READ_TIMEOUT, $params['read_timeout']))
  128. ) {
  129. $e = preg_replace('/^ERR /', '', $redis->getLastError());
  130. throw new InvalidArgumentException(sprintf('Redis connection failed (%s): %s', $e, $dsn));
  131. }
  132. return true;
  133. };
  134. if ($params['lazy']) {
  135. $redis = new RedisProxy($redis, $initializer);
  136. } else {
  137. $initializer($redis);
  138. }
  139. } elseif (is_a($class, \Predis\Client::class, true)) {
  140. $params['scheme'] = $scheme;
  141. $params['database'] = $params['dbindex'] ?: null;
  142. $params['password'] = $auth;
  143. $redis = new $class((new Factory())->create($params));
  144. } elseif (class_exists($class, false)) {
  145. throw new InvalidArgumentException(sprintf('"%s" is not a subclass of "Redis" or "Predis\Client"', $class));
  146. } else {
  147. throw new InvalidArgumentException(sprintf('Class "%s" does not exist', $class));
  148. }
  149. return $redis;
  150. }
  151. /**
  152. * {@inheritdoc}
  153. */
  154. protected function doFetch(array $ids)
  155. {
  156. if ($ids) {
  157. $values = $this->pipeline(function () use ($ids) {
  158. foreach ($ids as $id) {
  159. yield 'get' => [$id];
  160. }
  161. });
  162. foreach ($values as $id => $v) {
  163. if ($v) {
  164. yield $id => parent::unserialize($v);
  165. }
  166. }
  167. }
  168. }
  169. /**
  170. * {@inheritdoc}
  171. */
  172. protected function doHave($id)
  173. {
  174. return (bool) $this->redis->exists($id);
  175. }
  176. /**
  177. * {@inheritdoc}
  178. */
  179. protected function doClear($namespace)
  180. {
  181. // When using a native Redis cluster, clearing the cache is done by versioning in AbstractTrait::clear().
  182. // This means old keys are not really removed until they expire and may need garbage collection.
  183. $cleared = true;
  184. $hosts = [$this->redis];
  185. $evalArgs = [[$namespace], 0];
  186. if ($this->redis instanceof \Predis\Client) {
  187. $evalArgs = [0, $namespace];
  188. $connection = $this->redis->getConnection();
  189. if ($connection instanceof PredisCluster) {
  190. $hosts = [];
  191. foreach ($connection as $c) {
  192. $hosts[] = new \Predis\Client($c);
  193. }
  194. } elseif ($connection instanceof RedisCluster) {
  195. return false;
  196. }
  197. } elseif ($this->redis instanceof \RedisArray) {
  198. $hosts = [];
  199. foreach ($this->redis->_hosts() as $host) {
  200. $hosts[] = $this->redis->_instance($host);
  201. }
  202. } elseif ($this->redis instanceof \RedisCluster) {
  203. return false;
  204. }
  205. foreach ($hosts as $host) {
  206. if (!isset($namespace[0])) {
  207. $cleared = $host->flushDb() && $cleared;
  208. continue;
  209. }
  210. $info = $host->info('Server');
  211. $info = isset($info['Server']) ? $info['Server'] : $info;
  212. if (!version_compare($info['redis_version'], '2.8', '>=')) {
  213. // As documented in Redis documentation (http://redis.io/commands/keys) using KEYS
  214. // can hang your server when it is executed against large databases (millions of items).
  215. // Whenever you hit this scale, you should really consider upgrading to Redis 2.8 or above.
  216. $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;
  217. continue;
  218. }
  219. $cursor = null;
  220. do {
  221. $keys = $host instanceof \Predis\Client ? $host->scan($cursor, 'MATCH', $namespace.'*', 'COUNT', 1000) : $host->scan($cursor, $namespace.'*', 1000);
  222. if (isset($keys[1]) && \is_array($keys[1])) {
  223. $cursor = $keys[0];
  224. $keys = $keys[1];
  225. }
  226. if ($keys) {
  227. $host->del($keys);
  228. }
  229. } while ($cursor = (int) $cursor);
  230. }
  231. return $cleared;
  232. }
  233. /**
  234. * {@inheritdoc}
  235. */
  236. protected function doDelete(array $ids)
  237. {
  238. if ($ids) {
  239. $this->redis->del($ids);
  240. }
  241. return true;
  242. }
  243. /**
  244. * {@inheritdoc}
  245. */
  246. protected function doSave(array $values, $lifetime)
  247. {
  248. $serialized = [];
  249. $failed = [];
  250. foreach ($values as $id => $value) {
  251. try {
  252. $serialized[$id] = serialize($value);
  253. } catch (\Exception $e) {
  254. $failed[] = $id;
  255. }
  256. }
  257. if (!$serialized) {
  258. return $failed;
  259. }
  260. $results = $this->pipeline(function () use ($serialized, $lifetime) {
  261. foreach ($serialized as $id => $value) {
  262. if (0 >= $lifetime) {
  263. yield 'set' => [$id, $value];
  264. } else {
  265. yield 'setEx' => [$id, $lifetime, $value];
  266. }
  267. }
  268. });
  269. foreach ($results as $id => $result) {
  270. if (true !== $result && (!$result instanceof Status || $result !== Status::get('OK'))) {
  271. $failed[] = $id;
  272. }
  273. }
  274. return $failed;
  275. }
  276. private function pipeline(\Closure $generator)
  277. {
  278. $ids = [];
  279. if ($this->redis instanceof \Predis\Client && !$this->redis->getConnection() instanceof ClusterInterface) {
  280. $results = $this->redis->pipeline(function ($redis) use ($generator, &$ids) {
  281. foreach ($generator() as $command => $args) {
  282. \call_user_func_array([$redis, $command], $args);
  283. $ids[] = $args[0];
  284. }
  285. });
  286. } elseif ($this->redis instanceof \RedisArray) {
  287. $connections = $results = $ids = [];
  288. foreach ($generator() as $command => $args) {
  289. if (!isset($connections[$h = $this->redis->_target($args[0])])) {
  290. $connections[$h] = [$this->redis->_instance($h), -1];
  291. $connections[$h][0]->multi(\Redis::PIPELINE);
  292. }
  293. \call_user_func_array([$connections[$h][0], $command], $args);
  294. $results[] = [$h, ++$connections[$h][1]];
  295. $ids[] = $args[0];
  296. }
  297. foreach ($connections as $h => $c) {
  298. $connections[$h] = $c[0]->exec();
  299. }
  300. foreach ($results as $k => list($h, $c)) {
  301. $results[$k] = $connections[$h][$c];
  302. }
  303. } elseif ($this->redis instanceof \RedisCluster || ($this->redis instanceof \Predis\Client && $this->redis->getConnection() instanceof ClusterInterface)) {
  304. // phpredis & predis don't support pipelining with RedisCluster
  305. // see https://github.com/phpredis/phpredis/blob/develop/cluster.markdown#pipelining
  306. // see https://github.com/nrk/predis/issues/267#issuecomment-123781423
  307. $results = [];
  308. foreach ($generator() as $command => $args) {
  309. $results[] = \call_user_func_array([$this->redis, $command], $args);
  310. $ids[] = $args[0];
  311. }
  312. } else {
  313. $this->redis->multi(\Redis::PIPELINE);
  314. foreach ($generator() as $command => $args) {
  315. \call_user_func_array([$this->redis, $command], $args);
  316. $ids[] = $args[0];
  317. }
  318. $results = $this->redis->exec();
  319. }
  320. foreach ($ids as $k => $id) {
  321. yield $id => $results[$k];
  322. }
  323. }
  324. }