資料庫查詢通常是 PHP 應用最大瓶頸:網路延遲、查詢執行、結果傳輸、物件映射。Memcached 將熱門資料物件存入記憶體,微秒級存取,大幅降低 DB 負載與回應時間。
[PHP App] --> [Memcached Client] --> [Memcached Server 叢集]
│ │
└----------> [MySQL] (快取未命中時) <--┘
# 伺服端
apt update && apt install memcached libmemcached-tools
# 客戶端 PHP 擴充
apt install php-memcached # 推薦:libmemcached 基礎,功能完整
# 或
pecl install memcached # 手動編譯需 --enable-memcached --with-libmemcached-dir
啟動服務:systemctl enable --now memcached,預設監聽 11211 port。
addServer('127.0.0.1', 11211);
// 生產環境加多台:$mem->addServers([['host1',11211], ['host2',11211]]);
$key = 'article:123';
$article = $mem->get($key);
if ($article === false) { // 快取未命中
// 從 DB 讀取
$pdo = new PDO('mysql:host=localhost;dbname=blog', 'user', 'pass');
$stmt = $pdo->prepare('SELECT * FROM articles WHERE id = ?');
$stmt->execute([123]);
$article = $stmt->fetch(PDO::FETCH_ASSOC);
// 寫入快取,TTL 300 秒
$mem->set($key, $article, 300);
}
echo json_encode($article);
getDelayed + fetchAll 或分散式鎖delete 或 replace 快取;關鍵資料用「先刪快取再更新 DB」+ 重試機制# 即時統計
memcached-tool 127.0.0.1:11211 stats
# 關鍵指標
get_hits / (get_hits + get_misses) > 90% 命中率
evictions 頻繁表示記憶體不足
curr_connections 連線數
bytes / limit_maxbytes 記憶體使用率
| 特性 | Memcached | Redis |
|---|---|---|
| 資料結構 | 單純 Key-Value | String/Hash/List/Set/SortedSet/Stream |
| 持久化 | 無 | RDB/AOF 可選 |
| 複寫/HA | Client 端 | 內建 Sentinel/Cluster |
| Lua 腳本 | 無 | 支援原子操作 |
| 適用場景 | 純快取、大量小物件 | 快取+佇列+排行榜+Session+分散式鎖 |
現代架構常 兩者並用:Memcached 做純快取,Redis 做複雜資料結構與持久化需求。