问题背景

某支付系统PHP脚本内存占用从50MB持续增长至2GB,GC无法回收

三阶定位法

  1. Xdebug初筛

    xdebug_start_trace("/tmp/trace.xt");
    // 模拟1000次请求
    xdebug_stop_trace();
  2. 内存快照对比

    # 请求前
    php -r "echo memory_get_usage();" > before.log
    
    # 请求后
    php leak_script.php
    php -r "echo memory_get_usage();" > after.log
  3. 引用链破解

    // 全局变量追踪器
    register_shutdown_function(function() {
     file_put_contents("/tmp/globals.log", var_export($GLOBALS, true));
    });

真凶定位

未unset的Redis长连接导致内存无法回收(

$redis = new Redis();
$redis->connect("127.0.0.1", 6379);
// 缺少 $redis->close()

修复后单请求内存下降76%