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

PEAR 入門教程 (二):Cache_Lite 實戰 - 從頁面片段到資料物件快取

     編輯:PHP 綜合知識

為什麼選擇 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';
?>

核心配置選項

選項型別預設說明
cacheDirstring/tmp/快取檔案目錄,必須可寫,建議專案專用目錄
lifeTimeint3600快取存活秒數,0=永久 (需手動清理)
automaticCleaningFactorint10每 N 次寫入觸發一次舊檔清理,0=關閉
hashedDirectoryLevelint0子目錄層級分散檔案,大量快取時建議 1~2
fileLockingbooltrue啟用 flock 防止並發損壞
writeControlbooltrue寫入後驗證檔案完整性
readControlbooltrue讀取時驗證校驗和
readControlTypestringcrc32校驗演算法:crc32/md5/sha1
pearErrorModeconstCACHE_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;
}
?>

快取失效策略

  1. 時間過期:lifeTime 到期自動失效。
  2. 主動刪除:資料異動時呼叫 $cache->remove($id) 或 $cache->clean('group_name') (需啟用 cacheFileGroup)。
  3. 標籤/群組: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 一致,否則反序列化可能亂碼。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved