|
#!/usr/bin/env python
#coding:utf-8
import MySQLdb
import torndb
sql_s = "show slave status"
sql_m = "show master status"
# 使用MySQLdb的连接
def db_conM(args):
# args = {'host':[mhost,shost],'user':user,'passwd':passwd,'db':db,'port':3306,'con_timeout':5}
# 有从库时,判断延迟,大于50则连接主库
if args['host'][1] != '' :
try:
sdb = MySQLdb.connect(host=args['host'][1],port=args['port'],user=args['user'],passwd=args['passwd'],db=args['db'],charset="utf8",connect_timeout=args['con_timeout'])
except Exception,e:
sdb = MySQLdb.connect(host=args['host'][0],port=args['port'],user=args['user'],passwd=args['passwd'],db=args['db'],charset="utf8",connect_timeout=10)
return sdb
cursor = sdb.cursor()
cursor.execute(sql_s)
seconds = int(cursor.fetchall()[0][32])
if seconds > 50 :
sdb = MySQLdb.connect(host=args['host'][0],port=args['port'],user=args['user'],passwd=args['passwd'],db=args['db'],charset="utf8",connect_timeout=10)
return sdb
# 没有从库时,直接连接主库
try:
sdb = MySQLdb.connect(host=args['host'][0],port=args['port'],user=args['user'],passwd=args['passwd'],db=args['db'],charset="utf8",connect_timeout=10)
except Exception,e:
print "Connect failed:%s"%e
return
# cursor = sdb.cursor()
return sdb
# 使用torndb的连接,判断方法类似
def get_conT(args):
# args = {'host':[mhost,shost],'user':user,'passwd':passwd,'db':db,'port':3306,'con_timeout':5}
if args['host'][1] != '':
try:
sdb = torndb.Connection("%s:%s"%(args['host'][0],3306),args['db'],user=args['user'],password=args['passwd'],time_zone='+8:00',charset='utf8',connect_timeout=args['con_timeout'])
except Exception,e:
sdb = torndb.Connection("%s:%s"%(args['host'][1],3306),args['db'],user=args['user'],password=args['passwd'],time_zone='+8:00',charset='utf8',connect_timeout=10)
return sdb
seconds = int(sdb.get(sql_s).Seconds_Behind_Master)
if seconds > 50 :
sdb = torndb.Connection("%s:%s"%(args['host'][1],3306),args['db'],user=args['user'],password=args['passwd'],time_zone='+8:00',charset='utf8',connect_timeout=10)
return sdb
try:
sdb = torndb.Connection("%s:%s"%(args['host'][1],3306),args['db'],user=args['user'],password=args['passwd'],time_zone='+8:00',charset='utf8',connect_timeout=10)
except Exception,e:
print "Connect failed:%s"%e
return
return sdb
|
|