This repository has been archived on 2023-08-20. You can view files and clone it, but cannot push or open issues or pull requests.
symfony/src/Symfony/Component/Cache/Adapter/RedisAdapter.php

320 lines
12 KiB
PHP
Raw Normal View History

2016-01-19 13:27:46 +00:00
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Cache\Adapter;
use Predis\Connection\Factory;
use Predis\Connection\Aggregate\PredisCluster;
use Predis\Connection\Aggregate\RedisCluster;
2017-03-07 11:10:36 +00:00
use Predis\Response\Status;
2016-03-15 10:06:34 +00:00
use Symfony\Component\Cache\Exception\InvalidArgumentException;
2016-01-19 13:27:46 +00:00
/**
* @author Aurimas Niekis <aurimas@niekis.lt>
* @author Nicolas Grekas <p@tchwork.com>
2016-01-19 13:27:46 +00:00
*/
class RedisAdapter extends AbstractAdapter
{
private static $defaultConnectionOptions = array(
'class' => null,
'persistent' => 0,
'persistent_id' => null,
'timeout' => 30,
'read_timeout' => 0,
'retry_interval' => 0,
);
2016-01-19 13:27:46 +00:00
private $redis;
/**
Fix @param in PHPDoc Errors reported by Sami API Doc generator on branch 3.2 ERROR: The "factory" @param tag variable name is wrong (should be "objectLoader") on "Symfony\Bridge\Doctrine\Form\ChoiceList\DoctrineChoiceLoader::__construct" in src/Symfony/Bridge/Doctrine/Form/ChoiceList/DoctrineChoiceLoader.php:68 ERROR: The "objectLoader" @param tag variable name is wrong (should be "factory") on "Symfony\Bridge\Doctrine\Form\ChoiceList\DoctrineChoiceLoader::__construct" in src/Symfony/Bridge/Doctrine/Form/ChoiceList/DoctrineChoiceLoader.php:68 ERROR: "7" @param tags are expected but only "6" found on "Symfony\Bundle\WebProfilerBundle\Controller\ProfilerController::__construct" in src/Symfony/Bundle/WebProfilerBundle/Controller/ProfilerController.php:50 ERROR: "3" @param tags are expected but only "2" found on "Symfony\Component\Asset\PathPackage::__construct" in src/Symfony/Component/Asset/PathPackage.php:35 ERROR: "2" @param tags are expected but only "1" found on "Symfony\Component\Cache\Adapter\PhpArrayAdapter::create" in src/Symfony/Component/Cache/Adapter/PhpArrayAdapter.php:64 ERROR: "3" @param tags are expected but only "1" found on "Symfony\Component\Cache\Adapter\RedisAdapter::__construct" in src/Symfony/Component/Cache/Adapter/RedisAdapter.php:39 ERROR: The "format" @param tag variable name is wrong (should be "fileLinkFormat") on "Symfony\Component\Debug\ExceptionHandler::setFileLinkFormat" in src/Symfony/Component/Debug/ExceptionHandler.php:90 ERROR: "2" @param tags are expected but only "3" found on "Symfony\Component\DependencyInjection\Compiler\Compiler::addPass" in src/Symfony/Component/DependencyInjection/Compiler/Compiler.php:73 ERROR: "2" @param tags are expected but only "3" found on "Symfony\Component\DependencyInjection\Compiler\PassConfig::addPass" in src/Symfony/Component/DependencyInjection/Compiler/PassConfig.php:97 ERROR: "2" @param tags are expected but only "3" found on "Symfony\Component\DependencyInjection\ContainerBuilder::addCompilerPass" in src/Symfony/Component/DependencyInjection/ContainerBuilder.php:311 ERROR: "2" @param tags are expected but only "3" found on "Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\DumperInterface::getProxyFactoryCode" in src/Symfony/Component/DependencyInjection/LazyProxy/PhpDumper/DumperInterface.php:41 ERROR: "0" @param tags are expected but only "1" found on "Symfony\Component\HttpFoundation\Request::isMethodSafe" in src/Symfony/Component/HttpFoundation/Request.php:1458 ERROR: "5" @param tags are expected but only "6" found on "Symfony\Component\Serializer\Normalizer\AbstractNormalizer::instantiateObject" in src/Symfony/Component/Serializer/Normalizer/AbstractNormalizer.php:291
2017-03-28 22:38:21 +01:00
* @param \Redis|\RedisArray|\RedisCluster|\Predis\Client $redisClient The redis client
* @param string $namespace The default namespace
* @param integer $defaultLifetime The default lifetime
*/
public function __construct($redisClient, $namespace = '', $defaultLifetime = 0)
2016-01-19 13:27:46 +00:00
{
2016-05-02 13:16:25 +01:00
parent::__construct($namespace, $defaultLifetime);
2016-03-15 10:06:34 +00:00
if (preg_match('#[^-+_.A-Za-z0-9]#', $namespace, $match)) {
throw new InvalidArgumentException(sprintf('RedisAdapter namespace contains "%s" but only characters in [-+_.A-Za-z0-9] are allowed.', $match[0]));
}
if (!$redisClient instanceof \Redis && !$redisClient instanceof \RedisArray && !$redisClient instanceof \RedisCluster && !$redisClient instanceof \Predis\Client) {
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)));
}
2016-05-02 13:16:25 +01:00
$this->redis = $redisClient;
2016-01-19 13:27:46 +00:00
}
/**
* Creates a Redis connection using a DSN configuration.
*
* Example DSN:
* - redis://localhost
* - redis://example.com:1234
* - redis://secret@example.com/13
* - redis:///var/run/redis.sock
* - redis://secret@/var/run/redis.sock/13
*
* @param string $dsn
* @param array $options See self::$defaultConnectionOptions
*
* @throws InvalidArgumentException When the DSN is invalid.
*
2016-06-29 06:42:25 +01:00
* @return \Redis|\Predis\Client According to the "class" option
*/
public static function createConnection($dsn, array $options = array())
{
if (0 !== strpos($dsn, 'redis://')) {
throw new InvalidArgumentException(sprintf('Invalid Redis DSN: %s does not start with "redis://"', $dsn));
}
$params = preg_replace_callback('#^redis://(?:(?:[^:@]*+:)?([^@]*+)@)?#', function ($m) use (&$auth) {
if (isset($m[1])) {
$auth = $m[1];
}
return 'file://';
}, $dsn);
if (false === $params = parse_url($params)) {
throw new InvalidArgumentException(sprintf('Invalid Redis DSN: %s', $dsn));
}
if (!isset($params['host']) && !isset($params['path'])) {
throw new InvalidArgumentException(sprintf('Invalid Redis DSN: %s', $dsn));
}
if (isset($params['path']) && preg_match('#/(\d+)$#', $params['path'], $m)) {
$params['dbindex'] = $m[1];
$params['path'] = substr($params['path'], 0, -strlen($m[0]));
}
$params += array(
'host' => isset($params['host']) ? $params['host'] : $params['path'],
'port' => isset($params['host']) ? 6379 : null,
'dbindex' => 0,
);
if (isset($params['query'])) {
parse_str($params['query'], $query);
$params += $query;
}
$params += $options + self::$defaultConnectionOptions;
$class = null === $params['class'] ? (extension_loaded('redis') ? \Redis::class : \Predis\Client::class) : $params['class'];
2016-05-02 13:16:25 +01:00
if (is_a($class, \Redis::class, true)) {
$connect = $params['persistent'] || $params['persistent_id'] ? 'pconnect' : 'connect';
2016-05-02 13:16:25 +01:00
$redis = new $class();
@$redis->{$connect}($params['host'], $params['port'], $params['timeout'], $params['persistent_id'], $params['retry_interval']);
2016-05-02 13:16:25 +01:00
if (@!$redis->isConnected()) {
$e = ($e = error_get_last()) && preg_match('/^Redis::p?connect\(\): (.*)/', $e['message'], $e) ? sprintf(' (%s)', $e[1]) : '';
throw new InvalidArgumentException(sprintf('Redis connection failed%s: %s', $e, $dsn));
}
2016-05-02 13:16:25 +01:00
if ((null !== $auth && !$redis->auth($auth))
|| ($params['dbindex'] && !$redis->select($params['dbindex']))
|| ($params['read_timeout'] && !$redis->setOption(\Redis::OPT_READ_TIMEOUT, $params['read_timeout']))
) {
$e = preg_replace('/^ERR /', '', $redis->getLastError());
throw new InvalidArgumentException(sprintf('Redis connection failed (%s): %s', $e, $dsn));
}
} elseif (is_a($class, \Predis\Client::class, true)) {
$params['scheme'] = isset($params['host']) ? 'tcp' : 'unix';
$params['database'] = $params['dbindex'] ?: null;
$params['password'] = $auth;
$redis = new $class((new Factory())->create($params));
2016-05-02 13:16:25 +01:00
} elseif (class_exists($class, false)) {
throw new InvalidArgumentException(sprintf('"%s" is not a subclass of "Redis" or "Predis\Client"', $class));
2016-05-02 13:16:25 +01:00
} else {
throw new InvalidArgumentException(sprintf('Class "%s" does not exist', $class));
}
return $redis;
}
2016-01-19 13:27:46 +00:00
/**
* {@inheritdoc}
*/
protected function doFetch(array $ids)
{
if ($ids) {
2017-03-07 11:10:36 +00:00
$values = $this->pipeline(function () use ($ids) {
foreach ($ids as $id) {
yield 'get' => array($id);
}
});
foreach ($values as $id => $v) {
if ($v) {
yield $id => parent::unserialize($v);
}
2016-01-19 13:27:46 +00:00
}
}
}
/**
* {@inheritdoc}
*/
protected function doHave($id)
{
return (bool) $this->redis->exists($id);
2016-01-19 13:27:46 +00:00
}
/**
* {@inheritdoc}
*/
2016-03-15 10:06:34 +00:00
protected function doClear($namespace)
2016-01-19 13:27:46 +00:00
{
// When using a native Redis cluster, clearing the cache cannot work and always returns false.
// Clearing the cache should then be done by any other means (e.g. by restarting the cluster).
$cleared = true;
$hosts = array($this->redis);
$evalArgs = array(array($namespace), 0);
if ($this->redis instanceof \Predis\Client) {
$evalArgs = array(0, $namespace);
$connection = $this->redis->getConnection();
if ($connection instanceof PredisCluster) {
$hosts = array();
foreach ($connection as $c) {
$hosts[] = new \Predis\Client($c);
}
} elseif ($connection instanceof RedisCluster) {
return false;
}
} elseif ($this->redis instanceof \RedisArray) {
$hosts = array();
foreach ($this->redis->_hosts() as $host) {
$hosts[] = $this->redis->_instance($host);
}
} elseif ($this->redis instanceof \RedisCluster) {
return false;
}
foreach ($hosts as $host) {
if (!isset($namespace[0])) {
$cleared = $host->flushDb() && $cleared;
continue;
}
$info = $host->info('Server');
$info = isset($info['Server']) ? $info['Server'] : $info;
if (!version_compare($info['redis_version'], '2.8', '>=')) {
// As documented in Redis documentation (http://redis.io/commands/keys) using KEYS
// can hang your server when it is executed against large databases (millions of items).
// Whenever you hit this scale, you should really consider upgrading to Redis 2.8 or above.
$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;
continue;
}
$cursor = null;
do {
$keys = $host instanceof \Predis\Client ? $host->scan($cursor, 'MATCH', $namespace.'*', 'COUNT', 1000) : $host->scan($cursor, $namespace.'*', 1000);
if (isset($keys[1]) && is_array($keys[1])) {
$cursor = $keys[0];
$keys = $keys[1];
}
if ($keys) {
$host->del($keys);
}
} while ($cursor = (int) $cursor);
2016-03-15 10:06:34 +00:00
}
return $cleared;
2016-01-19 13:27:46 +00:00
}
/**
* {@inheritdoc}
*/
protected function doDelete(array $ids)
{
if ($ids) {
$this->redis->del($ids);
}
2016-01-19 13:27:46 +00:00
return true;
}
/**
* {@inheritdoc}
*/
protected function doSave(array $values, $lifetime)
{
$serialized = array();
2016-03-15 10:06:34 +00:00
$failed = array();
foreach ($values as $id => $value) {
2016-03-15 10:06:34 +00:00
try {
$serialized[$id] = serialize($value);
2016-03-15 10:06:34 +00:00
} catch (\Exception $e) {
$failed[] = $id;
2016-01-19 13:27:46 +00:00
}
2016-03-15 10:06:34 +00:00
}
if (!$serialized) {
return $failed;
}
2017-03-07 11:10:36 +00:00
$results = $this->pipeline(function () use ($serialized, $lifetime) {
foreach ($serialized as $id => $value) {
2017-03-07 11:10:36 +00:00
if (0 >= $lifetime) {
yield 'set' => array($id, $value);
} else {
yield 'setEx' => array($id, $lifetime, $value);
}
}
});
2017-03-07 11:10:36 +00:00
foreach ($results as $id => $result) {
if (true !== $result && (!$result instanceof Status || $result !== Status::get('OK'))) {
$failed[] = $id;
}
}
2016-03-15 10:06:34 +00:00
return $failed;
2016-01-19 13:27:46 +00:00
}
2017-03-07 11:10:36 +00:00
private function pipeline(\Closure $generator)
{
2017-03-07 11:10:36 +00:00
$ids = array();
2017-03-07 11:10:36 +00:00
if ($this->redis instanceof \Predis\Client) {
$results = $this->redis->pipeline(function ($redis) use ($generator, &$ids) {
foreach ($generator() as $command => $args) {
call_user_func_array(array($redis, $command), $args);
$ids[] = $args[0];
}
2017-03-07 11:10:36 +00:00
});
} elseif ($this->redis instanceof \RedisArray) {
$connections = $results = $ids = array();
foreach ($generator() as $command => $args) {
if (!isset($connections[$h = $this->redis->_target($args[0])])) {
$connections[$h] = array($this->redis->_instance($h), -1);
$connections[$h][0]->multi(\Redis::PIPELINE);
}
2017-03-07 11:10:36 +00:00
call_user_func_array(array($connections[$h][0], $command), $args);
$results[] = array($h, ++$connections[$h][1]);
$ids[] = $args[0];
}
foreach ($connections as $h => $c) {
$connections[$h] = $c[0]->exec();
}
foreach ($results as $k => list($h, $c)) {
$results[$k] = $connections[$h][$c];
}
2017-03-07 11:10:36 +00:00
} else {
$this->redis->multi(\Redis::PIPELINE);
foreach ($generator() as $command => $args) {
call_user_func_array(array($this->redis, $command), $args);
$ids[] = $args[0];
}
$results = $this->redis->exec();
}
foreach ($ids as $k => $id) {
yield $id => $results[$k];
}
}
2016-01-19 13:27:46 +00:00
}