APCu (APC User Cache) 是 APC 剝離 opcode 緩存後的用戶數據緩存組件。PHP 5.5+ 內置 Zend OPcache 處理 opcode 緩存,APCu 專注**用戶態數據共享內存緩存**,適用於單機/多進程(PHP-FPM worker)數據共享場景:配置緩存、會話存儲、計算結果緩存、限流計數器。
extension=apcu
apc.enabled=1
apc.shm_size=128M
apc.ttl=3600
apc.gc_ttl=3600
apc.enable_cli=1
# PECL 安裝(推薦)
pecl install apcu
# 或指定版本:pecl install apcu-5.1.22
# 編譯安裝
wget https://pecl.php.net/get/apcu-5.1.22.tgz
tar -zxf apcu-5.1.22.tgz
cd apcu-5.1.22
phpize
./configure --with-php-config=/usr/local/php/bin/php-config --enable-apcu
make && make install
# php.ini 添加
extension=apcu.so
apc.enabled=1
apc.shm_size=256M
apc.ttl=7200
apc.gc_ttl=3600
apc.enable_cli=1
php -m | grep apcu
php -r "apcu_store('k','v'); var_dump(apcu_fetch('k'));"
# 瀏覽器訪問 apc.php(源碼包含)查看統計面板
| 參數 | 默認 | 說明 | 調優建議 |
|---|---|---|---|
apc.enabled | 1 | 總開關 | 生產開啟,CLI 可關 |
apc.shm_size | 32M | 共享內存大小 | 按數據量設置,留 20% 余量。大內存機器 256M-1G |
apc.shm_segments | 1 | 共享內存段數 | 通常 1。若受限於系統 shmmax 可增段 |
apc.ttl | 0 | 條目存活秒數(0=永不過期) | **建議 3600-7200**。0 導致滿內存無法淘汰新數據 |
apc.gc_ttl | 3600 | GC 列表條目存活秒數 | 源文件修改後舊 opcode 緩存保護期 |
apc.entries_hint | 4096 | 預估條目數(槽位提示) | 約為預計 key 數 1.2-1.5 倍,減少rehash |
apc.slam_defense | 1 | 防犇騰機制(概率跳過寫入) | 高併發寫入場景設 75-100 |
apc.serializer | default | 序列化器 | php、igbinary(更快、更小)、msgpack |
apc.enable_cli | 0 | CLI 模式啟用 | 測試/腳本開啟,生產 CLI 關閉 |
apc.preload_path | 啟動預載目錄 | 部署時預熱熱點數據 |
<?php
// 寫入:$ttl 秒過期(0=永久,受 apc.ttl 限制)
apcu_store('key', $value, $ttl = 3600);
// 讀取:成功返回值,失敗返回 false(需用 $success 區分 false 值)
$value = apcu_fetch('key', $success);
if (!$success) { /* miss */ }
// 原子操作:獲取並刪除
$value = apcu_fetch('key');
apcu_delete('key');
// 原子增減(計數器、限流)
$count = apcu_inc('counter'); // +1
$count = apcu_dec('counter'); // -1
$count = apcu_inc('counter', 5); // +5
// 批量操作
apcu_store(['k1'=>'v1', 'k2'=>'v2']);
$vals = apcu_fetch(['k1','k2']);
// 緩存統計
$info = apcu_cache_info(); // 命中率、內存使用、條目數
$keys = apcu_cache_info('user'); // 列出所有 key(慎用大量 key 時)
// 迭代器(PHP 7+)
foreach (new APCUIterator() as $entry) {
// $entry['key'], $entry['value'], $entry['ttl'], ...
}
// 清空緩存
apcu_clear_cache();
?>
function getUser(int $id): ?array {
$key = "user:$id";
if (($data = apcu_fetch($key, $success)) && $success) {
return $data;
}
$data = $db->query("SELECT * FROM users WHERE id=?", $id)->fetch();
if ($data) apcu_store($key, $data, 3600);
return $data;
}
function updateUser(int $id, array $data): bool {
$ok = $db->update('users', $data, ['id' => $id]);
if ($ok) apcu_delete("user:$id"); // 失效策略:更新時刪除
return $ok;
}
function getExpensiveData(string $key, callable $callback, int $ttl = 3600) {
$lockKey = "lock:$key";
$data = apcu_fetch($key, $success);
if ($success) return $data;
// 獲取分布式鎖(這裡用 APCu 模擬,生產用 Redis SETNX)
if (apcu_add($lockKey, 1, 10)) { // 10s 鎖超時
try {
$data = $callback();
apcu_store($key, $data, $ttl);
} finally {
apcu_delete($lockKey);
}
return $data;
}
// 未獲取鎖:等待或返回舊數據/默認值
usleep(rand(50000, 200000)); // 50-200ms 抖動
return apcu_fetch($key, $s) ? $s : $callback(); // 兜底執行
}
function checkRateLimit(string $key, int $limit, int $window): bool {
$count = apcu_inc($key);
if ($count === false) {
apcu_store($key, 1, $window);
return true;
}
if ($count === 1) {
// 首次,設置 TTL(apcu_inc 不支援 TTL,需配合)
apcu_store($key, 1, $window); // 覆蓋設置 TTL
}
return $count <= $limit;
}
| 維度 | APCu | Redis | Memcached |
|---|---|---|---|
| 架構 | 單機進程內共享內存 | 網絡服務、集群 | 網絡服務、集群 |
| 延遲 | **極低(內存直讀,無網絡)** | 亞毫秒級(網絡 RTT) | 亞毫秒級 |
| 持久化 | 無(重啟丟失) | RDB/AOF 可選 | 無 |
| 數據結構 | K-V(字符串/序列化對象) | 豐富(Hash/List/Set/ZSet/Stream) | K-V |
| 多服務器共享 | **不支援** | 支援 | 支援 |
| 適用場景 | 單機熱點數據、配置、會話、計數器 | 分佈式緩存、會話、隊列、排行榜 | 簡單 K-V 緩存、Session |
apc.ttl > 0 允許 LRU 淘汰,監控 apcu_cache_info()['expired'] 與內存使用率。igbinary 擴展,設置 apc.serializer=igbinary,序列化速度提升 2-3 倍、體積減 30-50%。app:module:type:id,便於調試、清理、監控。APCu 是**單機高性能共享內存緩存**的利器:零網絡開銷、微秒級讀寫、原子操作豐富。核心適用場景:單機/多進程(FPM worker)熱點數據緩存、配置中心本地鏡像、限流計數器、會話存儲(單機)。跨機器、持久化、豐富數據結構需求請轉 Redis。配置關鍵:shm_size 足夠大、ttl > 0 允許淘汰、serializer=igbinary、監控命中率與內存水位。