Laravel 使用多个标签刷新缓存

Laravel flush cache with more than one tag

我在 Laravel 5.2 上使用 Redis 缓存,我的密钥有 2 个标签(基本上),年份和来源。

示例:

$this->cache->tags(['online', 2016])->put("key1", $value1, 10));
$this->cache->tags(['online', 2016])->put("key2", $value2, 10));
$this->cache->tags(['online', 2017])->put("key3", $value3, 10));
$this->cache->tags(['online', 2017])->put("key4", $value4, 10));

$this->cache->tags(['database', 2016])->put("key5", $value5, 10));
$this->cache->tags(['database', 2016])->put("key6", $value6, 10));
$this->cache->tags(['database', 2017])->put("key7", $value7, 10));
$this->cache->tags(['database', 2017])->put("key8", $value8, 10));

我想刷新标签 2016 和在线的缓存。

使用此 $this->cache->tags(['online', 2016])->flush(); 它将使用 any 标签刷新所有内容,即 online 2016(在本例中为 key1、key2、key3、key4、key5、key6)。

我想删除所有内容,包括 所有 标签,即 both online2016 (在这种情况下只有 key1 和 key2)

所以这需要一些挖掘,但这是结论。

是的,这在技术上是可能的(最好的可能?)

首先,RedisTaggedCache(负责在redis中实现tagging)将所有的tag member key存储在一个redis set中。以下是如何发现它的位置以及如何获得所有密钥:

function getAllTagKeys($cache,$tags) {
    $tagStore = new TagSet($cache->getStore(),$tags);
    $key = "<prefix>:{$tagStore->getNamespace()}:". RedisTaggedCache::REFERENCE_KEY_STANDARD;//use REFERENCE_KEY_FOREVER if the keys are cached forever or both one after the other to get all of them
    return collect($cache->getRedis()->smembers($key));
}

那么你可以这样做:

getAllTagKeys($this->cache, ["online"])
    ->insersect(getAllTagKeys($this->cache, ["2016"]))
    ->each(function ($v) {
         $this->cache->getRedis()->del();
     });

这看起来很糟糕。也许向 Laravel 提出功能请求更明智,因为这看起来像是他们应该公开的东西?

'yourKeyGoesHere'中,您可以插入一个与*相同的字符串,或者直接插入完全相同的键。

//Get all cached data ... 
$redis = Cache::getRedis();
$a_keys = $redis->keys("*yourKeyGoesHere*");
foreach ($a_keys as $key){
  //Your Action on key ... (Example delete / forget)
  $redis->del($key);
 }

我想我会做一个适合删除的键...

$this->cache->tags([andKey('online', 2016)])->put("key1", $value1, 10)); 
$this->cache->tags([andKey('online', 2016)])->put("key2", $value2, 10));
    
$this->cache->tags([andKey('online', 2016)])->flush();

helper:
function andKey($a, $b)
{
   return sprintf("%s.%s", $a, $b);  
}

多做一些工作,但在更改缓存系统时会省去很多麻烦。

编辑: 正如评论中所建议的那样,您可以添加所有键并刷新任何 3.

$this->cache->tags(['online', '2016', andKey('online', 2016)])->put("key1", $value1, 10)); 
$this->cache->tags(['online', '2016', andKey('online', 2016)])->put("key2", $value2, 10));
   
$this->cache->tags([andKey('online', 2016)])->flush();

helper:
function andKey($a, $b)
{
   return sprintf("combined.%s.%s", $a, $b);  
}