简体   繁体   English

"在 Symfony 5 中使用带有标记的 Redis"

[英]Using Redis with tagging in Symfony 5

trying to use Redis with tagging in my Symfony 5 app but can't seem to get RedisTagAwareAdapter to work.尝试在我的 Symfony 5 应用程序中使用带有标记的 Redis,但似乎无法让 RedisTagAwareAdapter 工作。 Saving to Redis without tags works just fine like this:保存到没有标签的 Redis 就像这样工作得很好:

use Symfony\Component\Cache\Adapter\RedisAdapter;
use Symfony\Contracts\Cache\ItemInterface;

$client = RedisAdapter::createConnection(
    'redis://redis'
);
$cache = new RedisAdapter($client);

$key = "testkey";
$data = "hello world";

$cacheItem = $cache->getItem($key);
$cacheItem->set($data);
$cacheItem->expiresAfter(3600);
$cache->save($cacheItem);

But if I switch to using the RedisTagAwareAdapter as this suggests then nothing gets saved:但是,如果我按照这建议切换到使用 RedisTagAwareAdapter,则不会保存任何内容:

use Symfony\Component\Cache\Adapter\RedisAdapter;
use Symfony\Component\Cache\Adapter\RedisTagAwareAdapter;
use Symfony\Contracts\Cache\ItemInterface;

$client = RedisAdapter::createConnection(
    'redis://redis'
);
$cache = new RedisTagAwareAdapter($client);

$key = "testkey";
$data = "hello world";

$cacheItem = $cache->getItem($key);
$cacheItem->set($data);
$cacheItem->tag('greeting');
$cacheItem->expiresAfter(3600);
$cache->save($cacheItem);

the $cache->save() returns false. $cache->save() 返回 false。 No other errors are thrown.不会引发其他错误。

I'm using Symfony 5, Redis server version 6.2.5 and have phpredis installed.我正在使用 Symfony 5、Redis 服务器版本 6.2.5 并安装了 phpredis。 Any ideas on what I'm doing wrong?关于我做错了什么的任何想法? TIA TIA

The solution makes everything a lot simpler :D该解决方案使一切变得更加简单:D

The CacheAdapter (from DoctrineCache2.x) makes things -although a bit weird - loads simpler. CacheAdapter(来自 DoctrineCache2.x)使事情 - 虽然有点奇怪 - 加载更简单。

In your case the code would look like this:在您的情况下,代码如下所示:

[...]
$cacheItem = $cache->get($key, function(ItemInterface $item) {
    $item->expire(3600);
    $item->tag('greeting');
    return "hello world";
});

Now I know this looks a bit counterproductive and makes hardly any sense at a first glance but here's what actually happens:现在我知道这看起来有点适得其反,乍一看几乎没有任何意义,但这是实际发生的情况:

first it tries to get the item at $key and if that is not a hit, the function callback gets into action.首先,它尝试在$key处获取项目,如果这不是命中,则函数回调开始执行。 It will create a new item, set the tagging and lifetime and it will assign the return value as the value stored at key (that is the weird part).它将创建一个新项目,设置标记和生命周期,并将返回值分配为存储在键中的值(这是奇怪的部分)。 And while it looks convoluted it's actually really smart since all the data gathering is being done ONLY if there's not cache hit for that specific key.虽然它看起来很复杂,但实际上非常聪明,因为只有在没有针对该特定键的缓存命中时才会完成所有数据收集。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM