以手機排行榜專案為例,示範如何使用 Memcache 儲存每 15 分鐘更新的前三名資料,避免重複查詢資料庫。
排行榜每 15 分鐘刷新,前三名需發獎品。使用 Memcache 快取前三名資訊,設定過期時間至當天結束。
public function getChargeRank3() {
$startime = '2014-04-10 00:00:00';
$endtime = '2014-04-30 23:59:59';
$sql = "select top 3 user_id, sum(point) as total from table
where state=5 and cp_id>=11 and cp_id<=19
and pay_time >= '$startime' and pay_time <= '$endtime'
group by user_id order by total desc";
$result = Yii::app()->db->createCommand($sql)->queryAll();
$key = 'charge_rank_top3';
$cache = Yii::app()->cache->get($key);
if ($cache !== false) {
foreach ($result as $key => $val) {
// 內部贈送禮物邏輯
}
}
Yii::app()->cache->set($key, $result, strtotime($endtime)); // 寫入快取
}
關鍵點:Yii::app()->cache 需在設定檔啟用 CMemCache 元件。快取鍵值設計需唯一,過期時間依業務邏輯設定。