Firestorm
Firestorm

Reputation: 157

Doctrine EntityManager not closed after mySQL connection times out, how to reconnect?

I have a ThruWay router (long running process) for which clients authenticate using wampcra. I use an EntityManager which I get from the Symfony service container to verify passwords. When mySQL's wait_timeout is reached, clients can no longer get authenticated.

I have read other similar questions and their answers and tried all I could find, I have the following snippet in place:

if(!$this->em->isOpen()) {
    $this->console->debug('EntityManager->isOpen() returned false.');
    $this->em = $this->registry->resetManager();
} else {
    $this->console->debug('EntityManager->isOpen() returned true.');
}
$b = $this->em->getConnection()->connect();
if($b) {
    $this->console->debug('EntityManager reconnected.');
} else {
    $this->console->debug('EntityManager still connected. Good.');
}

I set mySQL's wait_timeout to 120 (2 minutes) to debug this issue. The fact that after this period clients can no longer connects verifies that it's indeed the timeout that's the culprit. However, the isOpen() call returns true and getConnection()->connect() returns false even after the timeout expires:

EntityManager->isOpen() returned true.
EntityManager still connected. Good.

After the timeout an exception occurs even with forementioned code in place:

Warning: PDOStatement::execute(): MySQL server has gone away

What am I doing wrong here? How can I detect the connection is closed and reopen it if it is?

Upvotes: 1

Views: 1273

Answers (1)

Firestorm
Firestorm

Reputation: 157

I was perhaps a bit quick to ask this question as I've just found the answer, but someone else might benefit so I'm answering:

if(!$this->em->getConnection()->ping() || !$this->em->isOpen())

The ping() will return false if mySQL "went away" and the subsequent code that's run will effectively re-establish the connection.

Upvotes: 1

Related Questions