今天同事需要清理memcache中某種前綴的key的值,但memcache沒有專門的這種命令,我幫忙在網上找了一段程序:
How about this function in php: function deletekeysbyindex($prefix) { $m = new Memcached(); $m->addServer('localhost', 11211); $keys = $m->getAllKeys(); foreach ($keys as $index => $key) { if (strpos($key,$prefix) !== 0) { unset($keys[$index]); } else { $m->delete($key); } } return $keys; } Deletes keys beginning with $prefix and returns a list of all keys removed. I ran this on 30,000+ keys just now on a shared server and it was pretty quick - probably less than one second.
同事采用了這種辦法,可以列出、删除某種前綴的key的鍵值對,不過打印的時候,key中包含的中文沒有顯示,不确定是否正确。
我在網上去搜了一些資料,中文的資料比較少而且說法不一,多數說需要對中文進行編碼再做key,英文資料多一些,也有些說法不一,可能是memcache新老版本的問題,最後看到memcache隻有這幾種不能作為key:Keys cannot have spaces, new lines, carriage returns, or null characters. 其它的應該都可以。
https://github.com/pinterest/pymemcache/issues/122 這裡說: memcached supports unicode for both keys and values. Example run against a local memcached. So we don't need to do any hashing for unicode keys. $ echo -e 'add my☃ 0 60 11\r\nhello ☃ld\r' | nc localhost 11211 STORED $ echo -e 'get my☃\r' | nc localhost 11211 VALUE my☃ 0 11 hello ☃ld END
我自己檢查了以前在一個drupal網站中使用emoji做key的一部分的情況,memcached是可以自動進行urlencode編碼的:
最後同事直接在PHP程序中逐段調試,也證明可以直接用中文作為key的一部分,add和get都是OK的。👌
這也說明一個問題,網上資料不一定靠譜,最終還是要自己實踐來證實!
评论