Reconnecting MySQL on timeout

萝らか妹 提交于 2019-12-03 06:34:29

You have to catch the exception and based on which error, reconnect or to do something else. Whether it is a connection time out, or a network problem or the MySQL had to be restarted.

The below (pseudoish) code shows how you could do that, but there is more to it. You'll want to try a few times and then bail out, or maybe try every 2 minutes or so.

while True:
    try:
        # do your database stuff
    except peewee.OperationalError as exc:
        # Oops! We have to try to reconnect

Does not really matter whether you use an ORM or not. However, an ORM might offer this functionality.

I had the same problem and for peewee using MySQLdb I got the following solution when initialize the MySQL database instance:

db = MySQLDatabase(db_name, user=db_username, passwd=db_password, host=db_host, port=db_port)
db.get_conn().ping(True)

where for the ping function there is:

Checks whether or not the connection to the server is working. If it has gone down, an automatic reconnection is attempted.

This function can be used by clients that remain idle for a long while, to check whether or not the server has closed the connection and reconnect if necessary.

New in 1.2.2: Accepts an optional reconnect parameter. If True, then the client will attempt reconnection. Note that this setting is persistent. By default, this is on in MySQL<5.0.3, and off thereafter.

Non-standard. You should assume that ping() performs an implicit rollback; use only when starting a new transaction. You have been warned.

in the db.get_conn().ping.__doc__. Mind that db.get_conn().ping(True) has to be used if you create another connection again. So if you reconnect (through db.connect() for example) you must repeat the ping.

I have resolved this issue.

My solution is use mysql connection pool PooledMySQLDatabase from playhouse.pool module.

please read: https://github.com/coleifer/peewee/issues/239

from peewee import *
from playhouse.pool import *
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!