优化OPcache配置的3种实战方案

根据环境选择策略:

方案 A:开发环境(零延迟)

复制代码
; php.ini 或 .user.ini
opcache.enable=1
opcache.validate_timestamps=1
opcache.revalidate_freq=0  ; 每次请求都检查,牺牲性能换实时性

方案 B:生产环境(平衡策略)

保持 revalidate_freq=60 以获取性能,但在部署脚本中主动刷新:

复制代码
# 部署后执行
php -r "opcache_reset();"
# 或优雅地仅失效特定文件
php -r "opcache_invalidate('/path/to/config.php', true);"

方案 C:安装程序(代码层强制刷新)

最优雅的做法:不修改服务器配置,在安装代码中处理:

复制代码
/**
 * 安全写入配置并强制 OPcache 失效
 */
function install_write_config(string $file, array $config): bool
{
    $content = "<?php\nreturn " . var_export($config, true) . ";\n";
    
    // 原子写入
    $result = file_put_contents($file, $content, LOCK_EX);
    
    if (!$result) return false;
    
    // 关键:立即让 OPcache 失效该文件
    if (function_exists('opcache_invalidate')) {
        @opcache_invalidate($file, true); // true 表示强制刷新
    }
    
    // ThinkPHP 8 附加:清除运行时配置缓存
    $runtimeConfig = root_path() . 'runtime/config.php';
    if (file_exists($runtimeConfig)) {
        unlink($runtimeConfig);
    }
    
    return true;
}
相关推荐
xiangpingeasy2 年前
什么是OPcache?它对性能有什么影响?
php·opcache