Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[Cache] Add support for a tag lifetime in the RedisTagAwareAdapter #47509

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 30 additions & 3 deletions src/Symfony/Component/Cache/Adapter/RedisTagAwareAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,15 @@ class RedisTagAwareAdapter extends AbstractTagAwareAdapter
*/
private $redisEvictionPolicy;
private $namespace;
private $tagLifetime;

/**
* @param \Redis|\RedisArray|\RedisCluster|\Predis\ClientInterface|RedisProxy|RedisClusterProxy $redis The redis client
* @param string $namespace The default namespace
* @param int $defaultLifetime The default lifetime
* @param int|true|null $tagLifetime The tag life time to be used, can be either "null" for no lifetime, "true" for using the lifetime of the cache item or an int value that explicitly defines the lifetime
*/
public function __construct($redis, string $namespace = '', int $defaultLifetime = 0, MarshallerInterface $marshaller = null)
public function __construct($redis, string $namespace = '', int $defaultLifetime = 0, MarshallerInterface $marshaller = null, $tagLifetime = null)
{
if ($redis instanceof \Predis\ClientInterface && $redis->getConnection() instanceof ClusterInterface && !$redis->getConnection() instanceof PredisCluster) {
throw new InvalidArgumentException(sprintf('Unsupported Predis cluster connection: only "%s" is, "%s" given.', PredisCluster::class, \get_class($redis->getConnection())));
Expand All @@ -82,8 +84,13 @@ public function __construct($redis, string $namespace = '', int $defaultLifetime
}
}

if (true !== $tagLifetime && !is_numeric($tagLifetime) && null !== $tagLifetime) {
throw new InvalidArgumentException('Unsupported tag life time. Use either "null" for no tag life time, "true" for using the lifetime of the cache item or any int value that explicitly sets the tag life time.');
}

$this->init($redis, $namespace, $defaultLifetime, new TagAwareMarshaller($marshaller));
$this->namespace = $namespace;
$this->tagLifetime = $tagLifetime;
}

/**
Expand All @@ -101,13 +108,15 @@ protected function doSave(array $values, int $lifetime, array $addTagData = [],
return $failed;
}

$tagLifetime = $this->getTagLifetime($lifetime);
$itemLifetime = 0 >= $lifetime ? self::DEFAULT_CACHE_TTL : $lifetime;
// While pipeline isn't supported on RedisCluster, other setups will at least benefit from doing this in one op
$results = $this->pipeline(static function () use ($serialized, $lifetime, $addTagData, $delTagData, $failed) {
$results = $this->pipeline(static function () use ($serialized, $itemLifetime, $addTagData, $delTagData, $failed, $tagLifetime) {
// Store cache items, force a ttl if none is set, as there is no MSETEX we need to set each one
foreach ($serialized as $id => $value) {
yield 'setEx' => [
$id,
0 >= $lifetime ? self::DEFAULT_CACHE_TTL : $lifetime,
$itemLifetime,
$value,
];
}
Expand All @@ -116,6 +125,9 @@ protected function doSave(array $values, int $lifetime, array $addTagData = [],
foreach ($addTagData as $tagId => $ids) {
if (!$failed || $ids = array_diff($ids, $failed)) {
yield 'sAdd' => array_merge([$tagId], $ids);
if (null !== $tagLifetime) {
yield 'expire' => [$tagId, $tagLifetime];
}
}
}

Expand Down Expand Up @@ -318,4 +330,19 @@ private function getRedisEvictionPolicy(): string

return $this->redisEvictionPolicy = '';
}

private function getTagLifetime(int $itemLifetime): ?int
{
$tagLifetime = $this->tagLifetime;
if (true === $tagLifetime) {
$tagLifetime = $itemLifetime;
}

// The tag should never have a lower life time than the item.
if (is_numeric($tagLifetime) && $tagLifetime < $itemLifetime) {
$tagLifetime = $itemLifetime;
}

return $tagLifetime;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,56 @@ protected function setUp(): void
$this->skippedTests['testTagItemExpiry'] = 'Testing expiration slows down the test suite';
}

public function createCachePool(int $defaultLifetime = 0, string $testMethod = null): CacheItemPoolInterface
public function createCachePool(int $defaultLifetime = 0, string $testMethod = null, $tagLifetime = null): CacheItemPoolInterface
{
if ('testClearWithPrefix' === $testMethod && \defined('Redis::SCAN_PREFIX')) {
self::$redis->setOption(\Redis::OPT_SCAN, \Redis::SCAN_PREFIX);
}

$this->assertInstanceOf(RedisProxy::class, self::$redis);
$adapter = new RedisTagAwareAdapter(self::$redis, str_replace('\\', '.', __CLASS__), $defaultLifetime);
$adapter = new RedisTagAwareAdapter(self::$redis, str_replace('\\', '.', __CLASS__), $defaultLifetime, null, $tagLifetime);

return $adapter;
}

public function testTagExpiry()
{
$pool = $this->createCachePool(10, null, true);

$item = $pool->getItem('tag_item_expiry');
$item->tag(['tag_item_expiry_tag']);
$item->expiresAfter(5);

$pool->save($item);

sleep(7);

$redis = self::$redis;

$keys = $redis->keys('*tag_item_expiry*');
$this->assertCount(0, $keys);
}

public function testTagExpirySeparateLifetime()
{
$pool = $this->createCachePool(10, null, 10);

$item = $pool->getItem('tag_expiry');
$item->tag(['tag_expiry_tag']);
$item->expiresAfter(5);

$pool->save($item);

sleep(7);

$redis = self::$redis;

$keys = $redis->keys('*tag_expiry*');
$this->assertCount(1, $keys);

sleep(5);

$keys = $redis->keys('*tag_expiry*');
$this->assertCount(0, $keys);
}
}