在使用python2.7+django1.8时,Mysql报错 “mysql has gone away”,查看了其他博客后得知是因为连接超时,而且都有下面这种方法,少有人提到效率的问题,而效率是不得不考虑的事情(我们写操作比较多 mysql连接 平时都是没有问题的 但是一到周末就GG),所以亲自测一下
from django.db.backends.base.base import BaseDatabaseWrapper
import time
def close_old_connections():
for conn in connections.all():
conn.close_if_unusable_or_obsolete()
def close_if_unusable_or_obsolete(self):
"""
Closes the current connection if unrecoverable errors have occurred,
or if it outlived its maximum age.
"""
if self.connection is not None:
# If the application didn't restore the original autocommit setting,
# don't take chances, drop the connection.
if self.get_autocommit() != self.settings_dict['AUTOCOMMIT']:
LOG.warning('mysql connect close !!!!!')
self.close()
return
else:
LOG.warning('mysql has ckeck but do nothing !!!!!')
# If an exception other than DataError or IntegrityError occurred
# since the last commit / rollback, check if the connection works.
if self.errors_occurred:
if self.is_usable():
self.errors_occurred = False
else:
self.close()
return
if self.close_at is not None and time.time() >= self.close_at:
self.close()
return
BaseDatabaseWrapper.close_if_unusable_or_obsolete = close_if_unusable_or_obsolete
经过加上日志信息后发现,如果连接是正常的不会做任何事情,如果连接是无效的,会关闭旧连接,新建一个,对效率的影响不是很大,可以直接在经常报错的地方前面添加。