我有一个全天候运行的应用程序,它使用mysql。它的不同功能使用mysql。实现它的一种方法是在应用程序中创建一个全局mysql实例,如下所示:
self.db = MySQLdb.connect(
host=self.settings.MYSQL_HOST_LOCAL,
user=self.settings.MYSQL_USER,
passwd=self.settings.MYSQL_PASS,
db=self.settings.MYSQL_DB,
use_unicode=True,
charset="utf8",
)并使用self.db.execute(...)执行命令。通过这样做,应用程序使用1个连接。另一种方法是在每次需要执行事务时创建连接。
方法1,防止应用程序一次又一次地创建和删除连接,但如果保持理想,它将面临"mysql消失“的问题。方法2,没有"mysql消失“的问题,但是它有太多的I/O。
我非常确定这些approach都不是正确的,但是什么是正确的方法呢?
发布于 2013-10-18 09:31:36
一种方法是在每次需要执行时创建一个连接。您还可以创建一个函数来为您执行此操作。这就是它的本意。这不是太多的I/O。
您还可以执行以下操作:
while True:
try:
db_session.execute('SELECT * FROM table')
break
except SQLAlchemyError:
db_session.rollback()如果连接已经消失,这将引发异常,会话将被回滚,它将再次尝试,很可能会成功。(第一种解决方案要好得多)
发布于 2013-10-18 09:52:27
在方法1中,根据应用场景'MySQL服务器已经消失‘可能是因为
You have encountered a timeout on the server side and the automatic reconnection in the client is disabled (the reconnect flag in the MYSQL structure is equal to 0).你可以添加一个装饰器到任何数据库处理函数,当出现异常'MySQL服务器已经消失‘时,重新连接MySQL数据库。
class DB:
"""Database interface"""
def retry(func):
def call(self, *args, **kwargs):
lock.acquire()
try:
return func(self, *args, **kwargs)
except MySQLdb.Error, e:
if 'MySQL server has gone away' in str(e):
# reconnect MySQL
self.connect_mysql()
else:
# No need to retry for other reasons
pass
finally:
lock.release()
return call
def __init__(self):
pass
def connect_mysql(self):
# do connection
@retry
def db_handler_function(self):
# do somethinghttps://stackoverflow.com/questions/19440055
复制相似问题