内存耗尽现象与错误表现
现象描述
在处理 edu_ocr_img 表的数据归档任务过程中,每当处理数万条记录后,系统便会触发一次内存耗尽异常。
具体的错误提示为 PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 135168 bytes)。
经代码追踪定位,该问题源于插入操作期间的特定代码逻辑。
引发问题的具体语句为:EduOCRTaskBackup::getDb()->createCommand()->batchInsert(EduOCRTaskBackup::tableName(), $fields, $data)->execute();
执行 execute 方法后,内存占用显著上升,且即便后续对变量执行 unset 操作,仍有一部分内存无法释放,最终导致内存耗尽。
进一步深入 Yii2 源码,跟踪 execute 的具体实现,发现在记录日志环节存在高内存消耗。分析源码后,锁定造成泄漏的关键代码块。
相关泄漏代码片段展示
/**
* 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 Logger内存泄漏原理分析
内存泄漏成因深度解析
在 Yii2 框架的 vendor/yiisoft/yii2/log/Logger.php 文件中,第 156 行的 log 函数逻辑会在执行后判断条件 count($this->messages) >= $this->flushInterval 是否成立。
这意味着,只有当内存中存储的消息条目数大于或等于预设的 $this->flushInterval 值时,才会将消息刷写至磁盘。
若在达到刷新阈值之前,PHP.ini 配置的 128M 内存已被完全占用,系统将直接抛出内存申请耗尽的错误。
关于 YII2其他原因的内存泄漏的讨论 https://github.com/yiisoft/yii2/issues/13256
调整flushInterval与手动Flush策略
解决方案实施
建议在程序初始化阶段,将 flushInterval 配置为一个较小的数值。
\Yii::getLogger()->flushInterval = 100; // 设置成一个较小的值
在程序执行期间,每次 execute 操作完成后,主动对内存中的 message 进行 flush 处理。
\Yii::getLogger()->flush(true); // 参数传 true 表示每次都会将 message 清理到磁盘中
总结回顾
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对本站的支持。