gpt4 book ai didi

php - 教义刷新更改并释放内存

转载 作者:行者123 更新时间:2023-12-05 01:01:27 25 4
gpt4 key购买 nike

我在处理内存限制较低的 Symfony 项目时遇到问题。我需要创建几个实体,将它们添加到另一个实体(实体是关联的),然后将更改刷新到数据库。这发生在 while 循环中。

问题在于,有时循环无法完成整个循环,因为进程因内存耗尽而崩溃。我当然不能提高内存限制。

我试着用一些代码更好地解释你......

实体结构

class Device
{
/**
* @ORM\ManyToMany(targetEntity="Resource", inversedBy="devices",cascade={"persist", "refresh"}, fetch="EXTRA_LAZY")
*/
protected $resources;

public function addResource(Resource $resource)
{
if ($this->resources->contains($resource)) return;
$this->resources->add($resource);
$resource->addDevice($this);
}
}

class Resource
{
/**
* @ORM\ManyToMany(targetEntity="Device", mappedBy="resources")
*/
protected $devices;

public function addDevice(Device $device)
{
if ($this->devices->contains($device)) return;
$this->devices->add($device);
$device->addResource($this);
}
}

循环

function doIt(Device $device) {
while(...) {
$res = new Resource(...);
$device->addResource($res); // store $res in memory until end
}
$em->persist($device);
$em->flush();
}

所以问题是在循环结束之前,$device 一直在内存中保存 Resource 对象,有时会达到内存限制。

到目前为止我尝试了什么

function doIt(Device $device) {
$i = 0;
while(...) {
$res = new Resource(...);
$device->addResource($res);
$i++;
if ($i % 100 == 0) {
$em->persist($device);
$em->flush($device);
$device->setResources(null); // free up Resources in memory
$em->refresh($device); // Resources are not stored in memory
}
}
$em->persist($device);
$em->flush();
}

即使我看到内存增加(可能是由 Doctrine 引起的),这也不是那么好。此外,它们之间有很多实体和几个关联,在数据库中检查结果会给我一些错误(例如,实体没有持久化)。

你会怎么做?

最佳答案

您可以尝试一些方法来改善这种情况:

在导入的设置阶段禁用教条 SQL 日志记录机制

$this->getContainer()->get('doctrine')->getConnection()->getConfiguration()->setSQLLogger(null);

尝试定期调用 clear(我在处理和刷新一批项目后执行此操作),但请先阅读文档,因为根据您的代码可能会有副作用

$this->entityManager->clear();

您似乎已经清除了所有未使用的对象和变量,您也可以尝试在 php 中调用手动 gc_collect_cycle

gc_collect_cycles();

如果您的导入是使用 symfony 命令执行的,请确保您使用 --no-debug 标志启动它

在我的项目中使用导入命令运行良好,尽管它没有实现完全的内存中立,但剩余的泄漏可以忽略不计。也许这对你的情况有帮助。

关于php - 教义刷新更改并释放内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44416621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com