Memcache 是高併發架構中不可或缺的分布式內存緩存系統。本文系統梳理 Memcache 核心概念、PHP 擴展完整 API、關鍵操作詳解與工程落地經驗,助您構建高性能緩存層。
工作原理:內存中維護巨大 HashTable,非阻塞網絡 I/O(libevent),O(1) 讀寫,單實例支撐萬級 QPS。
┌─────────────┐ ┌──────────────┐
│ PHP 應用叢集 │◄───────►│ Memcached 叢集 │
│ (客戶端擴展) │ TCP:11211 │ (服務端守護進程) │
└─────────────┘ └──────────────┘
│ │
│ 一致性哈希分佈
│ (客戶端實現)
▼ ▼
會話存儲 數據分片與故障轉移
# CentOS/RHEL
yum install memcached -y
systemctl enable --now memcached
# Ubuntu/Debian
apt-get install memcached -y
systemctl enable --now memcached
# 配置 /etc/sysconfig/memcached (或 /etc/memcached.conf)
PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="512" # MB
OPTIONS="-l 0.0.0.0" # 監聽所有接口
# PECL 安裝 (推薦)
pecl install memcache
# 或編譯安裝:phpize && ./configure --enable-memcache && make install
# php.ini 啟用
extension=memcache.so
# 驗證
php -m | grep memcache
| 方法 | 用途 | 關鍵參數 | 返回值 |
|---|---|---|---|
connect(host, port, timeout) | 短連接 | host, port, timeout(秒) | bool |
pconnect(host, port, timeout) | 持久連接 | 同 connect | bool |
addServer(host, port, persistent, weight, timeout, retry_interval, status, failure_callback) | 添加服務器到連接池 | 權重、重試間隔、狀態回調 | bool |
set(key, var, flag, expire) | 存儲/覆寫 | 壓縮標記、過期秒數(≤2592000) | bool |
add(key, var, flag, expire) | 僅不存在時存儲 | 同 set | bool (存在返回 false) |
replace(key, var, flag, expire) | 僅存在時覆寫 | 同 set | bool (不存在返回 false) |
get(key) | 獲取單值 | key 或 key 陣列 | mixed/array/false |
getExtendedStats() | 所有服務器統計 | 無 | array |
getStats() | 單服務器統計 | type (items/slabs/sizes) | array |
increment(key, value) | 原子遞增 | 步長 (默認 1) | int/false |
decrement(key, value) | 原子遞減 | 步長 (默認 1) | int/false |
delete(key, timeout) | 刪除鍵 | 延遲刪除秒數 | bool |
flush() | 清空所有數據 | 立即生效 | bool |
close() | 關閉短連接 | 不影響持久連接 | bool |
setCompressThreshold(size, savings) | 壓縮閾值 | 最小字節、壓縮比 | bool |
getVersion() | 獲取版本 | 無 | string |
<?php
// 單實例短連接(請求結束自動關閉)
$m = new Memcache();
$m->connect('127.0.0.1', 11211);
// 持久連接(進程級復用,FPM/Worker 模式有效)
$m = new Memcache();
$m->pconnect('127.0.0.1', 11211);
// 連接池模式(推薦生產環境)
$m = new Memcache();
$m->addServer('10.0.0.1', 11211, true, 50); // 權重 50
$m->addServer('10.0.0.2', 11211, true, 50); // 權重 50
$m->addServer('10.0.0.3', 11211, true, 10); // 備用權重 10
// 客戶端自動一致性哈希分佈、故障轉移
核心原則:生產環境必須使用 addServer 連接池,配合持久連接,實現負載均衡與高可用。
| 場景 | 方法 | 語義 | 併發安全 |
|---|---|---|---|
| 緩存更新(允許覆蓋) | set | 無條件寫入 | 最後寫入勝 |
| 緩存初始化/鎖獲取 | add | 不存在才寫入 | ✅ 原子性,適合分布式鎖 |
| 確定存在時更新 | replace | 存在才覆蓋 | 防止誤創建 |
expire = 0:永不過期(實際受限於 LRU 淘汰)expire > 0 且 ≤ 2592000 (30天):相對秒數expire > 2592000:Unix 時間戳(絕對過期時間點)// 自動壓縮大於 20KB 的值,節省內存/網絡帶寬
$m->setCompressThreshold(20000, 0.2); // 節省 20% 以上才壓縮
$m->set('large_data', $bigJson, MEMCACHE_COMPRESSED, 3600);
<?php
$m = new Memcache();
$m->connect('localhost', 11211);
// 頁面訪問計數器
$key = 'page_view:article_123';
$m->set($key, 0); // 初始化
$views = $m->increment($key); // 原子 +1,返回新值
// 庫存扣減(防超賣)
$stockKey = 'stock:sku_456';
$m->set($stockKey, 100);
if ($m->decrement($stockKey) !== false) {
// 扣減成功,處理訂單
} else {
// 庫存不足
}
# php.ini
session.save_handler = memcache
session.save_path = "tcp://10.0.0.1:11211?persistent=1&weight=1,tcp://10.0.0.2:11211?persistent=1&weight=1"
memcache.hash_strategy = "consistent" # 關鍵:一致性哈希
md5($longKey))-I 參數調整,最大 128MB)$stats = $m->getExtendedStats();
/* 關注指標:
curr_items // 當前項數
bytes // 內存使用量
limit_maxbytes // 最大內存
get_hits / get_misses // 命中率 = hits/(hits+misses)
evictions // LRU 淘汰次數(>0 表明內存不足)
curr_connections // 當前連接數
*/
Memcache 以極簡協議、高性能內存存儲、客戶端智能路由成為緩存層首選。掌握連接池配置、原子操作、壓縮策略、一致性哈希等核心特性,並建立完善監控告警,是構建高可用高性能 PHP 系統的關鍵技能。