.php 原始碼 → 詞法分析 → 語法分析 → 編譯為 Opcode (中間碼)。無快取時:每請求重複步驟 2-3,CPU 大量消耗在編譯階段。
有 Opcode 快取:編譯結果存入共享記憶體,後續請求直接執行快取 Opcode,跳過編譯,大幅降低 CPU、縮短響應時間。
apc_cache_info、apc_store/fetch 等用戶快取 API。APC 拆分為:OPcache (核心 Opcode 快取) + APCu (用戶變數快取)。現代 PHP 專案:OPcache + APCu (或 Redis/Memcached)。
# PECL
pecl install apcu
# 或系統包管理
apt-get install php-apcu # Ubuntu/Debian
yum install php-pecl-apcu # CentOS/RHEL (EPEL)
[apcu]
extension = apcu.so
apc.enabled = 1
apc.shm_size = 128M # 共享記憶體大小,視資料量調整 (建議 64M-512M)
apc.ttl = 7200 # 項目存活秒數 (0=永不失效,但易導致碎片/滿)
apc.user_ttl = 7200 # 用戶快取 TTL
apc.gc_ttl = 3600 # 垃圾回收 TTL
apc.entries_hint = 4096 # 預估項目數,優化哈希表大小
apc.mmap_file_mask = /tmp/apc.XXXXXX ; 檔案映射模式 (Linux 推薦)
apc.enable_cli = 1 ; CLI 環境啟用 (方便測試/腳本)
apc.serializer = php ; 序列化器 (php/igbinary/msgpack)
apc.use_request_time = 1 ; 使用請求時間判斷 TTL
| 函數 | 用途 | 範例 |
|---|---|---|
apcu_store($key, $var, $ttl=0) | 儲存變數 | apcu_store('config', $arr, 3600); |
apcu_fetch($key, &$success) | 讀取變數 | $data = apcu_fetch('config', $ok); |
apcu_delete($key) | 刪除 | apcu_delete('config'); |
apcu_clear_cache() | 清空所有 | apcu_clear_cache(); |
apcu_cache_info() | 狀態資訊 | print_r(apcu_cache_info()); |
apcu_inc/dec($key, $step=1) | 原子增減 | apcu_inc('counter'); |
apcu_cas($key, $old, $new) | 比較並交換 (原子) | 無鎖計數器/分散式鎖基礎 |
apcu_key_info($key) | 鍵元資訊 | 檢查是否存在、建立時間、TTL |
| 維度 | APCu | Redis | Memcached |
|---|---|---|---|
| 儲存模型 | 本機共享記憶體 | 網路記憶體資料結構存儲 | 網路 Key-Value 記憶體 |
| 持久化 | 無 (重啟丟失) | RDB/AOF 可選 | 無 |
| 資料結構 | 單純 Key-Value | String/Hash/List/Set/ZSet/Stream | String |
| 分散式 | 不支援 (單機) | Cluster/Sentinel 原生支援 | Client 端一致性哈希 |
| 效能 (本機) | 極高 (無網路開銷) | 高 (本機 Unix Socket ~微秒) | 高 |
| 適用場景 | 單機熱點資料、Composer 快取、OPcache 補充 | 分散式快取、Session、佇列、排行榜、速率限制 | 簡單多節點快取、Session (舊專案) |
+----------------+ +----------------+ +----------------+
| Nginx |---->| PHP-FPM |---->| MySQL/Postgre |
| (靜態/快取) | | (OPcache) | | (主從/分片) |
+----------------+ +----------------+ +----------------+
|
+---------+---------+
| |
+-----v-----+ +-----v-----+
| APCu | | Redis |
| (本機熱點)| | (分散式) |
| 配置/字典 | | Session/ |
| 翻譯/權限 | | 隊列/鎖/ |
+-----------+ | 計數器 |
+-----------+
extension=apc.so,啟用 zend_extension=opcache.so + extension=apcu.so。apc_* 用戶快取呼叫改為 apcu_* (API 完全相容)。opcache.enable=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=20000
opcache.revalidate_freq=60 ; 生產 60 秒檢查一次,開發 0
opcache.fast_shutdown=1
opcache.jit=1255 ; PHP 8+ JIT 編譯
OPcache 解決 Opcode 快取,APCu/Redis 解決資料快取,分工明確,各司其職。