OPcache已生效需满足:浏览器访问phpinfo()页面显示“Opcode Caching”启用且opcache.enable=On;若无此区块或opcache_get_status()报错,则未加载。

确认OPcache是否在Web请求中真实生效
浏览器访问一个含<?php phpinfo(); ?>的info.php页面,搜索“Loaded Configuration File”并记下路径——后续所有修改必须作用于该文件,而非CLI配置或任意其他ini;页面中必须出现“Opcode Caching”区块且状态为Enabled,同时右侧opcache.enable显示On;若搜不到该区块,或执行var_dump(opcache_get_status());报错Call to undefined function opcache_get_status(),说明OPcache根本未加载进PHP-FPM进程。
这一步不能只看php -m | grep opcache有输出就认为OK——命令行启用≠FPM启用,两者配置完全隔离。
获取实时OPcache状态数据
在Web可访问目录下新建opcache-status.php,内容为:
<?php if (!function_exists('opcache_get_status')) { die('OPcache not available'); } $status = opcache_get_status(true); echo '<pre>' . htmlspecialchars(print_r($status, true)) . '</pre>; ?>
立即学习“PHP免费学习笔记(深入)”;
用浏览器打开该文件,重点查看opcache_statistics下的hits、misses、oom_restarts、max_memory_usage四项数值;若oom_restarts > 0,说明缓存内存已满被迫重置,【opcache.memory_consumption必须立即调高】;若hits / (hits + misses) < 0.85,大概率是opcache.validate_timestamps=1导致高频stat()拖垮I/O,而非缓存容量问题。
分析关键性能指标含义
第一步:计算缓存命中率 → hits ÷ (hits + misses),低于0.9说明大量请求仍走编译流程,性能增益被抵消;
第二步:检查opcache_statistics['num_cached_scripts']是否接近opcache.max_accelerated_files,若长期卡在95%以上,说明文件数上限已成瓶颈,缓存驱逐频繁;
第三步:观察opcache_statistics['max_memory_usage']是否持续高于opcache.memory_consumption × 0.9,超限即触发OOM重启,响应抖动必然发生;
第四步:核对opcache_statistics['start_time']与服务器当前时间差值,若超过部署时间却无变化,证明新代码根本没进缓存——此时opcache.validate_timestamps=0而你又没手动执行opcache_reset(),就是罪魁祸首。
快速定位缓存失效根源
方法一:检查opcache_get_status()['scripts']数组长度,若为空或远少于项目PHP文件总数,说明脚本根本未被缓存——常见原因是opcache.restrict_api设了非空路径前缀,而当前请求URL不匹配;
方法二:执行php -r "var_dump(opcache_is_script_cached('/var/www/html/index.php'));"(路径替换成你的真实入口),返回false即表示该文件未入缓存,需排查是否被opcache.blacklist_filename规则拦截;
方法三:在PHP-FPM错误日志中搜索OPcache: Failed to open script或Cannot redeclare class,这类报错往往伴随opcache.validate_timestamps=0且发布后未清缓存,旧opcode与新类定义冲突所致。
生产环境必备监控脚本
新建/usr/local/bin/opcache-check,内容如下:
#!/usr/bin/env php
<?php
$s = opcache_get_status(true);
if (!$s || $s['opcache_statistics']['oom_restarts'] > 0) { echo "CRITICAL: OOM restarts detected\n"; exit(2); }
if ($s['opcache_statistics']['hits'] / ($s['opcache_statistics']['hits'] + $s['opcache_statistics']['misses']) < 0.85) { echo "WARNING: Hit rate below 85%\n"; exit(1); }
echo "OK: Hit rate " . round($s['opcache_statistics']['hits'] / ($s['opcache_statistics']['hits'] + $s['opcache_statistics']['misses']) * 100, 1) . "%\n";
?>
赋予执行权限:chmod +x /usr/local/bin/opcache-check;加入crontab每5分钟执行一次:*/5 * * * * /usr/local/bin/opcache-check > /dev/null;当返回CRITICAL时,立即调大memory_consumption并reload PHP-FPM。



















