編輯 application/config/database.php:
$db['default']['cache_on'] = TRUE; $db['default']['cachedir'] = APPPATH . 'cache/db/'; // 確保目錄可寫
創建目錄:mkdir -p application/cache/db && chmod 777 application/cache/db
// 開啟緩存
$this->db->cache_on();
$query1 = $this->db->query("SELECT * FROM products WHERE status=1"); // 會被緩存
// 關閉緩存(用戶個性化數據)
$this->db->cache_off();
$query2 = $this->db->query("SELECT * FROM orders WHERE user_id={$this->session->uid}"); // 不緩存
// 重新開啟
$this->db->cache_on();
$query3 = $this->db->query("SELECT * FROM categories"); // 緩存
// 清除所有查詢緩存
$this->db->cache_delete_all();
// 清除特定控制器/方法的緩存
// 緩存文件按「控制器+方法」命名,如 blog+comments
$this->db->cache_delete('blog', 'comments'); // 對應 Blog::comments()
// 模型中寫操作後自動清理
public function update_product($id, $data) {
$this->db->where('id', $id)->update('products', $data);
$this->db->cache_delete('product', 'detail'); // 清除詳情頁緩存
$this->db->cache_delete('product', 'list'); // 清除列表頁緩存
}
application/cache/db/ ├── product+detail.html # Product::detail() 查詢結果序列化 ├── product+list.html └── blog+comments.html
| 場景 | 建議 |
|---|---|
| 靜態/半靜態頁面(首頁、列表、詳情) | 啟用緩存,寫操作後清理對應片段 |
| 用戶個性化數據(購物車、訂單、推薦) | 關閉緩存(cache_off()) |
| 高頻更新表(庫存、計數器) | 不緩存或極短 TTL(CI 原生不支持 TTL,需自行實現) |
| 開發/測試環境 | 關閉緩存(cache_on = FALSE)避免調試困擾 |
// 封裝帶 TTL 的緩存查詢
public function get_cached($table, $where, $ttl = 300) {
$key = md5($table . serialize($where));
$cache_file = $this->db->cachedir . $key . '.cache';
if (file_exists($cache_file) && (time() - filemtime($cache_file) < $ttl)) {
return unserialize(file_get_contents($cache_file));
}
$this->db->cache_on();
$result = $this->db->where($where)->get($table)->result_array();
$this->db->cache_off();
file_put_contents($cache_file, serialize($result));
return $result;
}