当前位置: 移动技术网 > IT编程>开发语言>PHP > Yii2 框架跑脚本时内存泄漏问题分析

Yii2 框架跑脚本时内存泄漏问题分析

2019年05月25日  | 移动技术网IT编程  | 我要评论

现象

在跑 edu_ocr_img 表的归档时,每跑几万个数据,都会报一次内存耗尽

php fatal error:  allowed memory size of 134217728 bytesexhausted (tried toallocate 135168 bytes)

跟踪代码发现,是在插入时以下代码造成的:

eduocrtaskbackup::getdb()->createcommand()->batchinsert(eduocrtaskbackup::tablename(), $fields, $data)->execute();

execute 之后会造成使用内存涨上去,并且在之后 unset 所有变量内存也会有一部分不会删除,直到内存耗尽。

于是跟踪到 yii2中execute的具体代码块发现在记录 log 的时候会将使用很高的内存,分析代码之后得出造成泄漏的代码块如下:

造成泄漏的代码块

/**
 * logs a message with the given type and category.
 * if [[tracelevel]] is greater than 0, additional call stack information about
 * the application code will be logged as well.
 * @param string|array $message the message to be logged. this can be a simple string or a more
 * complex data structure that will be handled by a [[target|log target]].
 * @param integer $level the level of the message. this must be one of the following:
 * `logger::level_error`, `logger::level_warning`, `logger::level_info`, `logger::level_trace`,
 * `logger::level_profile_begin`, `logger::level_profile_end`.
 * @param string $category the category of the message.
 */
public function log($message, $level, $category = 'application')
{
    $time = microtime(true);
    $traces = [];
    if ($this->tracelevel > 0) {
        $count = 0;
        $ts = debug_backtrace(debug_backtrace_ignore_args);
        array_pop($ts); // remove the last trace since it would be the entry script, not very useful
        foreach ($ts as $trace) {
            if (isset($trace['file'], $trace['line']) && strpos($trace['file'], yii2_path) !== 0) {
                unset($trace['object'], $trace['args']);
                $traces[] = $trace;
                if (++$count >= $this->tracelevel) {
                    break;
                }
            }
        }
    }
    
    // 这里是造成内存的罪魁祸首
    $this->messages[] = [$message, $level, $category, $time, $traces];
    if ($this->flushinterval > 0 && count($this->messages) >= $this->flushinterval) {
        $this->flush();
    }
}

造成内存泄漏的原因分析

在 yii2框架中的 vendor/yiisoft/yii2/log/logger.php:156 log函数的156行之后会判断 count($this->messages) >= $this->flushinterval
即:内存中存储的 message 的条数要大于等于预设的 $this->flushinterval 才会将内存中的message 刷到磁盘上去。

如果在刷新到磁盘之前就已经将 php.ini 设置的 128m 内存打满的话,会直接报错申请内存耗尽。

很多关于 yii2其他原因的内存泄漏的讨论

解决方案

  1. 在程序开始时,设置 flushinterval 为一个比较小的值
\yii::getlogger()->flushinterval = 100; // 设置成一个较小的值
  1. 在程序执行过程中,每次 execute 之后对内存中的 message 进行 flush
\yii::getlogger()->flush(true); // 参数传 true 表示每次都会将 message 清理到磁盘中

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网