守护程序中的 Doctrine2 连接超时

2022-01-16 00:00:00 php symfony doctrine doctrine-orm

我有一个长时间运行的守护进程(Symfony2 命令),它从 Redis 中的工作队列中获取工作,并使用 orm 执行这些工作并写入数据库.

I have a long running daemon (Symfony2 Command) that gets work off a work queue in Redis, and performs those jobs and writes to the database using the orm.

我注意到,当工作人员空闲等待工作时,由于与 MySQL 的连接超时,工作人员有死亡的趋势.

I noticed that when that there is a tendency for the worker to die because the connection to MySQL timed out when worker is idling waiting for work.

具体来说,我在日志中看到:MySQL Server has gone away.

Specifically, I see this in the log: MySQL Server has gone away.

无论如何我可以让学说自动重新连接吗?或者有什么方法可以手动捕获异常并重新连接学说 orm?

Is there anyway I can have doctrine automatically reconnect? Or is there some way I can manually catch the exception and reconnect the doctrine orm?

谢谢

推荐答案

看来,每当Doctrine中的EntityManager遇到任何错误/异常时,就会关闭连接,EntityManager死了.

It appears that whenever there is any error/exception encountered by the EntityManager in Doctrine, the connection is closed and the EntityManager is dead.

由于通常所有内容都包含在事务中,并且在调用 $entityManager->flush() 时执行该事务,因此您可以尝试捕获异常并尝试重新执行或放弃.

Since generally everything is wrapped in a transaction and that transaction is executed when $entityManager->flush() is called, you can try and catch the exception and attempt to re-excute or give up.

您可能希望通过更具体的类型捕获来检查异常的确切性质,无论是 PDOException 还是其他.

You may wish to examine the exact nature of the exception with more specific catch on the type, whether PDOException or something else.

对于 MySQL has Gone Away 异常,您可以尝试通过重置 EntityManager 来重新连接.

For a MySQL has Gone Away exception, you can try to reconnect by resetting the EntityManager.

$managerRegistry = $this->getContainer()->get('doctrine');
$em = $managerRegistry->getEntityManager();
$managerRegistry->resetEntityManager();

这应该使 $em 再次可用.请注意,您必须再次重新持久化所有内容,因为这个 $em 是新的.

This should make the $em usable again. Note that you would have to re-persist everything again, since this $em is new.

相关文章