Memcached 是高效能分散式記憶體快取系統,PHP 透過 memcached 擴展 (較新、功能全) 或舊版 memcache 連接。本文涵蓋基礎連線、生產級封裝類、所有方法速查表與最佳實踐。
# Ubuntu/Debian
apt-get install php-memcached memcached
# 檢查擴展
php -m | grep memcached
# 輸出: memcached (非 memcache)
?>
<?php
$mem = new Memcached();
$mem->addServer('127.0.0.1', 11211); // 可加多台組成叢集
// 設定鍵值 (過期秒數)
$mem->set('user:1', ['name' => 'Alice', 'level' => 10], 300);
// 取得
$data = $mem->get('user:1');
var_dump($data); // ['name'=>'Alice', 'level'=>10]
// 原子遞增/遞減 (計數器)
$mem->set('counter', 0);
$mem->increment('counter'); // 1
$mem->increment('counter', 5); // 6
$mem->decrement('counter'); // 5
// 多鍵一次取得
$items = $mem->getMulti(['user:1', 'user:2', 'counter']);
?>
<?php
class Cache {
private static ?Memcached $instance = null;
private static array $config = [
'servers' => [
['127.0.0.1', 11211, 33], // host, port, weight
// ['10.0.0.2', 11211, 66],
],
'options' => [
Memcached::OPT_BINARY_PROTOCOL => true,
Memcached::OPT_TCP_NODELAY => true,
Memcached::OPT_NO_BLOCK => true,
Memcached::OPT_CONNECT_TIMEOUT => 2000, // ms
Memcached::OPT_RETRY_TIMEOUT => 2, // sec
Memcached::OPT_DISTRIBUTION => Memcached::DISTRIBUTION_CONSISTENT,
Memcached::OPT_LIBKETAMA_COMPATIBLE => true,
Memcached::OPT_COMPRESSION => true, // 自動壓縮大值
Memcached::OPT_COMPRESSION_THRESHOLD => 1024, // >1KB 壓縮
Memcached::OPT_SERIALIZER => Memcached::SERIALIZER_IGBINARY, // 需 igbinary
],
'prefix' => 'myapp:', // 鍵前綴避免衝突
];
private function __construct() {}
public static function getInstance(): Memcached {
if (self::$instance === null) {
self::$instance = new Memcached();
foreach (self::$config['servers'] as [$host, $port, $weight]) {
self::$instance->addServer($host, $port, $weight);
}
self::$instance->setOptions(self::$config['options']);
}
return self::$instance;
}
// 統一加前綴
private static function key(string $key): string {
return self::$config['prefix'] . $key;
}
public static function set(string $key, mixed $value, int $ttl = 300): bool {
return self::getInstance()->set(self::key($key), $value, $ttl);
}
public static function get(string $key, mixed $default = null): mixed {
$val = self::getInstance()->get(self::key($key));
return $val ?? $default;
}
public static function delete(string $key): bool {
return self::getInstance()->delete(self::key($key));
}
public static function increment(string $key, int $offset = 1, int $initial = 0, int $ttl = 300): int|false {
$mem = self::getInstance();
$k = self::key($key);
if (!$mem->get($k)) {
$mem->set($k, $initial, $ttl);
}
return $mem->increment($k, $offset);
}
public static function decrement(string $key, int $offset = 1): int|false {
return self::getInstance()->decrement(self::key($key), $offset);
}
public static function flush(): bool {
return self::getInstance()->flush();
}
public static function stats(): array {
return self::getInstance()->getStats();
}
}
// 使用
Cache::set('session:abc123', ['uid'=>1001, 'role'=>'admin'], 1800);
$user = Cache::get('session:abc123');
Cache::increment('api:rate_limit:192.168.1.1');
?>
| 方法 | 說明 | 回傳 |
|---|---|---|
add($k, $v, $ttl) | 僅不存在時設定 | bool |
set($k, $v, $ttl) | 設定 (覆蓋) | bool |
replace($k, $v, $ttl) | 僅存在時覆蓋 | bool |
get($k) | 取得值 | mixed/false |
getMulti([$k1,$k2]) | 批次取得 | array |
getDelayed([$k1,$k2]) | 非阻塞批次取得 | bool |
fetch()/fetchAll() | 取得 getDelayed 結果 | mixed/array |
delete($k) | 刪除鍵 | bool |
increment($k, $offset) | 原子遞增 | int/false |
decrement($k, $offset) | 原子遞減 | int/false |
touch($k, $ttl) | 更新過期時間 | bool |
flush() | 清空所有 (慎用!) | bool |
getStats() | 伺服器統計 (命中率、記憶體、連線數) | array |
getVersion() | 伺服器版本 | array |
setOption/Option | 設定/取得客戶端選項 | bool/mixed |
addServer/$addServers | 新增伺服器節點 | bool |
quit() | 關閉所有連線 | bool |
DISTRIBUTION_CONSISTENT + LIBKETAMA_COMPATIBLE,節點增減不雪崩。igbinary 比 php 序列化快 2-3 倍、體積小 30-50%。Memcached 實例,避免重複建立 TCP 連線。get_hits / (get_hits + get_misses) 命中率 > 90% 為健康。