前置需求
- 伺服器安裝 Memcached 服務:
yum install memcached 或 apt-get install memcached
- PHP 安裝 memcached 擴充套件(非 memcache):
pecl install memcached
- 啟用擴充:
extension=memcached.so
快取介面定義
interface CacheInterface {
public function set($key, $value, $expire = 0);
public function get($key);
public function delete($key);
public function flush();
}
Memcached 實作類別
class MemcachedCache implements CacheInterface {
private $memcached;
private $servers = []; // 多伺服器支援
private $defaultServer = 0;
public function __construct(array $config = []) {
if (!class_exists('Memcached')) {
throw new Exception('Memcached 擴充套件未安裝');
}
$this->memcached = new Memcached();
// 預設配置
$defaultConfig = [
'servers' => [
['host' => '127.0.0.1', 'port' => 11211, 'weight' => 100]
],
'options' => [
Memcached::OPT_COMPRESSION => true,
Memcached::OPT_LIBKETAMA_COMPATIBLE => true, // 一致性雜湊
Memcached::OPT_BINARY_PROTOCOL => true,
]
];
$config = array_merge_recursive($defaultConfig, $config);
$this->servers = $config['servers'];
// 設定選項
foreach ($config['options'] as $opt => $val) {
$this->memcached->setOption($opt, $val);
}
$this->connect();
}
private function connect() {
$serverList = [];
foreach ($this->servers as $s) {
$serverList[] = [$s['host'], $s['port'], $s['weight'] ?? 100];
}
$this->memcached->addServers($serverList);
}
public function set($key, $value, $expire = 0) {
// 自動序列化複雜資料
$flags = is_scalar($value) ? 0 : Memcached::SERIALIZER_PHP;
return $this->memcached->set($key, $value, $expire, $flags);
}
public function get($key) {
return $this->memcached->get($key);
}
public function delete($key) {
return $this->memcached->delete($key);
}
public function flush() {
return $this->memcached->flush();
}
// 進階功能
public function getMulti(array $keys) {
return $this->memcached->getMulti($keys);
}
public function increment($key, $offset = 1, $initial = 0, $expire = 0) {
return $this->memcached->increment($key, $offset, $initial, $expire);
}
public function getStats() {
return $this->memcached->getStats();
}
}
使用範例
// 初始化(可從配置檔讀取)
$cache = new MemcachedCache([
'servers' => [
['host' => '10.0.0.1', 'port' => 11211],
['host' => '10.0.0.2', 'port' => 11211],
]
]);
// 基本操作
$cache->set('user:1001', ['name' => '張三', 'email' => 'zhang@example.com'], 3600);
$user = $cache->get('user:1001');
// 計數器(原子操作)
$cache->set('page_views', 0);
$views = $cache->increment('page_views'); // 1, 2, 3...
// 批量讀取
$profiles = $cache->getMulti(['user:1001', 'user:1002', 'user:1003']);
// 監控統計
$stats = $cache->getStats();
print_r($stats);
關鍵優化建議
- 鍵名規範:使用前綴分隔業務域(如
user:, session:, api:)
- 序列化選擇:預設 PHP 序列化相容性佳,效能敏感場景可改用
igbinary 或 msgpack
- 壓縮策略:大數據(>1KB)啟用壓縮
OPT_COMPRESSION
- 一致性雜湊:多伺服器必須啟用
OPT_LIBKETAMA_COMPATIBLE 避免節點變動導致大量失效
- 連線池:長連線減少握手開銷,PHP-FPM 工作進程間自動共享