Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine2 connection timeout in daemon

Tags:

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.

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.

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

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?

Thanks

like image 531
James Cowhen Avatar asked Dec 27 '12 19:12

James Cowhen


2 Answers

I'm using this in my symfony2 beanstalkd daemon Command worker:

$em = $this->getContainer()->get('doctrine')->getManager();
if ($em->getConnection()->ping() === false) {
    $em->getConnection()->close();
    $em->getConnection()->connect();
}
like image 135
tomcyr Avatar answered Sep 21 '22 08:09

tomcyr


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

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.

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

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();

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

like image 42
James Cowhen Avatar answered Sep 18 '22 08:09

James Cowhen