首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

Yii 框架 Memcache 快取實戰應用

     編輯:PHP 相關知識

Yii 框架 Memcache 快取實戰應用

以手機排行榜專案為例,示範如何使用 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 元件。快取鍵值設計需唯一,過期時間依業務邏輯設定。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved