python2中MySQLdb加入超时及其重试功能
定义一个状态,超时时间和重试的次数限制(此为样例代码,你可以把他们包装到函数或类中)
循环判断_conn_status状态且判断最大重试次数
在循环中try except 连接如果DB连接成功则_conn_status为False,异常except则_conn_retries_count次数加1,且continue操作
def reConndb():
_conn_status = True
_max_retries_count = 10 #设置最大重试次数
_conn_retries_count = 0 #初始重试次数
_conn_timeout = 3 # 连接超时时间为3秒
while _conn_staus and _conn_retries_count <= _max_retries_count:
try:
conn = db.connect(host=xxx, user=xxx, passwd=xxx, connect_timeout=_conn_timeout)
_conn_status = False # 如果conn成功则_status为设置为False则退出循环,返回db连接对象
return conn
except:
_conn_retries_count += 1
print _conn_retries_count
print 'connect db is error!!'
time.sleep(3) #此为测试看效果
continue
以上为带重试功能和连接超时功能的DB连接
转载于:https://blog.51cto.com/smly1989/1982404