2013-03-16 20 views
1

我在想如何使用Cache(MemCache)來顯示我在我的網站上有多少註冊用戶和活動用戶。我目前使用:如何使用Memcached來存儲給定時間的數據

return mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `active` = 1"), 0); 

而這不好用,因爲在每一頁加載時,它都會查詢數據庫。哪個不好。那麼我該如何去做一個「memcache」或類似的東西,在10分鐘左右之後,它會將這個數字更新爲所有用戶?

我使用Google搜索了一下,但是我無法真正瞭解如何使用它。

謝謝!

+0

任何人都知道這一點? – 2013-03-16 03:06:35

回答

3

我給你的指導方針,而不是一個完整的文檔/教程。

在嘗試安裝Memcached之前,您應該使用MySQLiPDO而不是mysql_ *函數。檢出this documentation中的警告消息。

您應該install Memcached及其PHP extension

一旦完成,請通過調用函數phpinfo()確保啓用它。如果Memcached不在那裏,安裝失敗。

這是一個明確的代碼片斷

$mc = new Memcached(); 
$mc->addServer('localhost', 11211); // add a new server to the pool 

// you will want to vary this key according to the query 
// if two different queries use the same key your functions will return unexpected data 
$cacheKey = 'a-custom-key-that-defines-the-data-within-it'; 

// how long will it take for the cache to expire in seconds : an hour 
$cacheLifetime = 3600; 

$data = $mc->get($cacheKey); // we get the data from cache 

// check if Memcached was able to retrieve the data 
if ($mc->getResultCode() === Memcached::RES_FAILURE) { 
    // if for some reasons the data is not there we get it and reinject into memcached 
    $data = mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `active` = 1"), 0); 

    $mc->set($cacheKey, $data, $cacheLifetime); // save the data in the defined $cacheKey 
} 

return $data; 
+0

好的,謝謝!我將不得不嘗試一下! – 2013-03-17 00:25:58

相關問題