簡體   English   中英

帶有多個標簽的 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(); 它將使用任何標簽刷新所有內容,即online2016 (在本例中為 key1、key2、key3、key4、key5、key6)。

我想刪除一切,包括所有的標簽,即,online2016 (在這種情況下,只有KEY1和KEY2)

所以這需要一些挖掘,但這是結論。

是的,這在技術上是可行的(最好的方法?)

首先, RedisTaggedCache (負責在redis中實現打標簽)將所有標簽成員鍵存儲在一個redis集合中。 以下是如何發現它在哪里以及如何獲得所有密鑰:

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 提出功能請求更明智,因為這看起來是他們應該公開的東西?

我想我會制作一個適合刪除的鍵...

$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);  
}

'yourKeyGoesHere' 中,您可以插入一個與 like 一樣使用的字符串,並帶有 * 或直接插入確切的鍵。

//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);
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM