本文目录导读:

在 PHP 项目中,清理 OPcache 缓存主要有以下几种方法:
使用函数清理(代码层面)
<?php
// 清空整个 OPcache
opcache_reset();
// 清除特定文件的缓存
opcache_invalidate('/path/to/file.php', true); // true 强制重新编译
注意:opcache_reset() 仅在 PHP CLI 模式下可能无效,需要 Web 环境或使用 --no-accumulation 参数。
通过 Web 页面手动清理
创建一个清理脚本 opcache_clear.php:
<?php
// 安全验证(推荐添加 Token 验证)
$token = 'your-secret-token';
if (!isset($_GET['token']) || $_GET['token'] !== $token) {
die('Access denied');
}
if (function_exists('opcache_reset')) {
$result = opcache_reset();
echo $result ? 'OPcache cleared successfully' : 'Failed to clear OPcache';
} else {
echo 'OPcache not enabled';
}
访问:http://your-domain.com/opcache_clear.php?token=your-secret-token
命令行方式(需要 CLI 权限)
# 重启 PHP-FPM(最彻底的方式) sudo systemctl restart php-fpm # CentOS/RHEL sudo systemctl restart php8.1-fpm # Ubuntu/Debian(根据 PHP 版本调整) # 或者使用 kill -USR2 信号 sudo kill -USR2 $(pgrep -x php-fpm)
通过 OPcache 管理工具
安装 opcache-gui
git clone https://github.com/amnuts/opcache-gui # 或直接下载 PHP 文件
将 opcache-gui.php 放到 Web 目录,访问即可看到管理界面,包含清除缓存按钮。
自动清理策略
设置缓存过期时间(修改 php.ini)
[opcache] opcache.enable=1 opcache.revalidate_freq=2 # 每 2 秒检查文件修改 opcache.validate_timestamps=1 # 启用时间戳验证 opcache.max_accelerated_files=7963 # 缓存文件数 opcache.memory_consumption=128 # 内存大小(MB) opcache.interned_strings_buffer=8 # 字符串缓存
快速开发环境清理
对于开发环境,推荐以下配置实现文件修改后自动更新:
opcache.revalidate_freq=0 opcache.validate_timestamps=1 opcache.file_update_protection=2 # 防止文件写入时的竞争条件
注意事项
-
生产环境谨慎操作:
opcache_reset()会清除所有已编译脚本,导致大量请求同时重新编译,可能造成短暂性能下降。 -
权限问题:Web 服务器用户需要有权限执行
opcache_reset()。 -
分布式环境:如果有多台服务器,需要在每台服务器上都执行清理操作。
-
定期清理策略:可以通过 crontab 设置定期清理:
# 每天凌晨 3 点清理 0 3 * * * /usr/bin/php -r "opcache_reset();"
推荐做法:对于生产环境,最好使用 opcache_invalidate() 单独清除修改过的文件,而不是全局重置。