標籤:自訂模板判斷mysql主從延遲
使用自訂模板
#!/usr/bin/env python#coding:utf-8import MySQLdbimport torndbsql_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
將檔案命名成db_help.py,後面的指令碼直接引用,判斷主從,切記在使用完串連後,記得關閉(sdb.close()的關閉)。
或者將以上兩個函數用class進行封裝,同時將sdb.close()函數定義在解構函式中,達到在對象使用完後,自動關閉串連的作用。
mysql延遲判斷模板