Magento – Disconnect & Reconnect MySQL core_read / core_write Connections

databaseMySQL

We have a process that runs within our Magento installation that:

  1. Bootstraps Magento
  2. Performs some actions which involve writing to a
    table in mysql
  3. Connects to a remote API, which takes a long time to
    respond (20mins +)
  4. Attempts to write more information to a table in
    mysql

The problem is, that due to the long time taken for the remote API to respond, the MySQL server has sometimes 'Gone Away' by the time we attempt to perform step 4. The simplest solution to this is to simply increase the wait_timeout for MySQL, but this feels like a hacky solution.

Is there a way from within Magento to close then reopen the database connection? Or even just force a reconnect after step 3? I tried to dig into it, but the actual instantiation of the connection seems (as with many things in Magento) deeply buried. I'm therefore unsure exactly how I might force a reconnect.

Best Answer

Yes, you can. Assuming you open the connection with something like this:

$db = Mage::getSingleton('core/resource')->getConnection('core_read');

You can close the connection with this:

$db->closeConnection();

And then re-open it with this:

$db->getConnection();

When I need to make an api call that could take a long time, I close the connection first, then use getConnection to open it again afterwards, which has solved the "mysql server has gone away" problem for me.

Related Topic