我需要一個可靠的測試來知道是否使用memcache Set或memcache替換。
這是我結束了。
另一種選擇是爲memcache查詢設置一個網絡套接字,但最終它會做同樣的事情,並且這個連接已經存在,從而節省了製作和維護另一個連接的開銷,就像Joel Chen的回答。
$key = 'test';
$value = 'foobarbaz';
/**
* Intricate dance to test if key exists.
* If it doesn't exist flags will remain a boolean and we need to use the method set.
* If it does exist it'll be set to integer indicating the compression and what not, then we need to use replace.
*/
$storageFlag = (is_null($value) || is_bool($value) || is_int($value) || is_float($value) ? false : MEMCACHE_COMPRESSED);
$flags = false;
$memcache->get($key, $flags);
if(false === $flags) {
$memcache->set($key, $value, storageFlag , $minutes);
}
else {
$memcache->replace($key, $value, storageFlag, $minutes);
}
現在,如果您有「大數據」,解決方案相當簡單。使用包含一些簡單的整數來檢查的聯合中的第二個鍵。總是一起使用它們,你沒有問題。
$key = 'test';
$value = 'foobarbaz';
$storageFlag = (is_null($value) || is_bool($value) || is_int($value) || is_float($value) ? false : MEMCACHE_COMPRESSED);
$flags = false;
$exist_key = $key.'_exists';
$memcache->get($exist_key, $flags);
if(false === $flags) {
$memcache->set($key, $value, storageFlag , $minutes);
$memcache->set($exist_key, 42, false , $minutes);
}
else {
$memcache->replace($key, $value, storageFlag, $minutes);
$memcache->replace($exist_key, 42, false , $minutes);
}
是的,但我首先需要確定它尚未設置。因爲如果它已經設置好了,那麼我會浪費從一個緩慢的來源讀取數據。如果我使用get()來檢查,那麼我將浪費網絡IO,因爲值爲1MB是大小。 – Matic 2010-06-22 07:41:13
@Matic「問題」是memcached沒有設計網絡IO,所以我想這就是爲什麼這種功能被省略的原因。如果網絡IO是一個問題,那麼你最好使用kv數據庫。我明白,即使網絡IO不是問題,但有時候您不需要額外分配,但memcached無法實現這一點。 Redis有這樣的功能。 – themihai 2016-04-22 16:32:23