為什麼選擇 Cache_Lite?
- 純 PHP 實現,無額外擴展依賴
- 支援 檔案式、共享記憶體 多種後端
- 內建 自動清理、鎖機制 防止緩存擊穿
- API 簡潔:
get() / save() / remove() / clean()
安裝與引入
# 有 pear 指令
pear install Cache_Lite-1.8.3
# 手動下載
# 解壓至 lib/pear/Cache/Lite.php
<?php
require_once 'bootstrap.php'; // 含 set_include_path
require_once 'Cache/Lite.php';
?>
核心配置選項
| 選項 | 型別 | 預設 | 說明 |
| cacheDir | string | /tmp/ | 快取檔案目錄,必須可寫,建議專案專用目錄 |
| lifeTime | int | 3600 | 快取存活秒數,0=永久 (需手動清理) |
| automaticCleaningFactor | int | 10 | 每 N 次寫入觸發一次舊檔清理,0=關閉 |
| hashedDirectoryLevel | int | 0 | 子目錄層級分散檔案,大量快取時建議 1~2 |
| fileLocking | bool | true | 啟用 flock 防止並發損壞 |
| writeControl | bool | true | 寫入後驗證檔案完整性 |
| readControl | bool | true | 讀取時驗證校驗和 |
| readControlType | string | crc32 | 校驗演算法:crc32/md5/sha1 |
| pearErrorMode | const | CACHE_LITE_ERROR_RETURN | 錯誤處理:RETURN/DIE/EXCEPTION |
基礎範例:頁面片段快取
<?php
require_once 'Cache/Lite.php';
$options = [
'cacheDir' => __DIR__ . '/storage/cache/',
'lifeTime' => 300, // 5 分鐘
'automaticCleaningFactor' => 20,
'hashedDirectoryLevel' => 1,
'fileLocking' => true,
'writeControl' => true,
];
$cache = new Cache_Lite($options);
$cacheId = 'homepage_blocks'; // 唯一標識
if ($data = $cache->get($cacheId)) {
echo $data; // 命中直接輸出
} else {
ob_start();
// --- 高耗時邏輯 ---
include 'blocks/header.php';
include 'blocks/slider.php';
include 'blocks/hot_products.php';
include 'blocks/footer.php';
// ------------------
$data = ob_get_clean();
$cache->save($data, $cacheId);
echo $data;
}
?>
進階:資料物件快取 (陣列/物件)
<?php
function getTopProducts(int $limit = 10): array {
global $cache;
$id = 'top_products_' . $limit;
if ($data = $cache->get($id)) {
return $data;
}
// 模擬資料庫查詢
$pdo = new PDO('mysql:host=localhost;dbname=shop', 'user', 'pass');
$stmt = $pdo->prepare('SELECT id, name, price FROM products ORDER BY sales DESC LIMIT ?');
$stmt->execute([$limit]);
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
$cache->save($data, $id);
return $data;
}
?>
快取失效策略
- 時間過期:
lifeTime 到期自動失效。
- 主動刪除:資料異動時呼叫
$cache->remove($id) 或 $cache->clean('group_name') (需啟用 cacheFileGroup)。
- 標籤/群組:
Cache_Lite_Function 或自行維護 cache_id => tags 對應表,批次清理相關快取。
效能調優建議
- 快取目錄掛載 tmpfs:
mount -t tmpfs -o size=256m tmpfs /var/www/storage/cache 將 I/O 移至記憶體。
- 避免序列化大物件:若資料結構複雜,考慮
igbinary 或 msgpack 序列化後存入,減少 CPU 開銷。
- 監控命中率:定期檢查
cacheDir 檔案數與大小,命中率 < 80% 需檢視 lifeTime 或快取粒度。
常見坑點
- 權限問題:Web 使用者 (www-data/apache) 必須對
cacheDir 有 rwx 權限。
- 快取雪崩:熱點快取同時過期導致大量請求穿透 DB,解法:
lifeTime 加入隨機抖動 (如 300 + rand(0,60))。
- 編碼不一致:儲存 UTF-8 資料時確保 PHP
default_charset 一致,否則反序列化可能亂碼。