[英]delete cache by prefix in apc / memcache / eaccelerator
假設我將這些變量保存在apc,memcached和eaccelerator中:
article_1_0
article_1_1
article_3_2
article_3_3
article_2_4
如何刪除以article_3_
開頭的所有緩存變量(它們最多可以達到10000)?
有沒有辦法列出緩存變量?
對於APC:
$iterator = new APCIterator('user', '#^article_3_#', APC_ITER_KEY);
foreach($iterator as $entry_name) {
apc_delete($entry_name);
}
對於eaccelerator:
foreach(eaccelerator_list_keys() as $name => $infos) {
if (preg_match('#^article_3_#', $name)) {
eaccelerator_rm($name);
}
}
對於memcached,請查看@ rik的答案
一次過期多個密鑰的一般解決方案是命名它們。 要使它們過期,您只需更改命名空間:
假設您有一組鍵“article_3_1”,“article_3_2”,....您可以像這樣存儲它們:
$ns = apc_fetch('article_3_namespace');
apc_store($ns."_article_3_1", $value);
apc_store($ns."_article_3_2", $value);
像這樣獲取它們:
$ns = apc_fetch('article_3_namespace');
apc_fetch($ns."_article_3_1");
只需遞增命名空間即可使它們全部到期:
apc_inc('article_3_namespace');
雖然文檔說APCIterator在apc> = 3.1.1中可用,但我在幾個聲稱擁有apc 3.1.9的系統上,但是沒有APCIterator存在。 如果您沒有APCIterator,請給這樣的東西一個旋轉:
$aCacheInfo = apc_cache_info('user');
foreach($aCacheInfo['cache_list'] as $_aCacheInfo)
if(strpos($_aCacheInfo['info'], 'key_prefix:') === 0)
apc_delete($_aCacheInfo['info']);
在這個例子中,我們檢查密鑰中的前綴,但是你可以使用preg_match等。 並實現更接近APCIterator提供的東西。
有一個APCIterator可以幫助您搜索APC中的密鑰。 實例化APCIterator。
APCIterator :: valid()表示仍有一些鍵仍在迭代中。 APCIterator :: key()返回apc鍵。 APCIterator :: next()將迭代器位置移動到下一個項目。
// APC
$iterator = new APCIterator('user', '/^article_3_/');
while($iterator->valid()) {
apc_delete($iterator->key());
// You can view the info for this APC cache value and so on by using
// $iterator->current() which is array
$iterator->next();
}
對於memcache,您可以使用Memcached並使用getAllKeys方法
// Memcached
$m = new Memcached();
$m->addServer('mem1.domain.com', 11211);
$items = $m->getAllKeys();
foreach($items as $item) {
if(preg_match('#^article_3_#', $item)) {
$m->delete($item);
}
}
有一種方法可以從memcache中檢索所有密鑰,但它非常昂貴。
如果有可能使用memcached的替代方法, scache支持結構化鍵空間。 有了它,您可以將數據存儲到嵌套路徑:
scache_shset($conn, 'article/1/0', $data10);
scache_shset($conn, 'article/3/0', $data30);
scache_shset($conn, 'article/3/1', $data31);
並最終通過刪除父節點來銷毀數據
scache_shunset($conn, 'article/3');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.