python自动结束mysql慢查询会话的实例代码
生产环境的有些sql查询写得太复杂,或是表很大,对应索引未建立或建立不合理,或是查询未充分使用索引等,就有可能出现慢查询,一些慢查询需要修改程序,可能没那么快能解决,这时如果有个脚本能自动检测符合条件的慢查询会话并结束,那么是很方便的,当然运维人员也可顺便弄个检测慢查询并告警的脚本。
涉及知识点
- mysql慢查询会话查询
- schedule定时任务调度
- pymysql执行sql
代码分解
mysql慢查询
#会话查询,只能查询所有会话,不能按条件过滤,不过比较好记
showPROCESSLIST;
#从information_schema中查询会话,可以按条件过滤
SELECT
*
FROM
information_schema.`PROCESSLIST`;
#查询符合条件的慢会话,id是会话ID,info是正在执行的sql,time是会话持续时间,杀会话时注意要做好过滤
SELECT
id,
info,
time
FROM
information_schema.`PROCESSLIST`
WHERE
infoLIKE'%select*fromtable%'
ANDtime>10;
#直接使用sql批量杀会话,拼接killxxx;后,拷贝了在控制台执行
SELECT
concat('KILL',id,';')
FROM
information_schema.`PROCESSLIST`
WHERE
infoLIKE'%select*fromtable%'
ANDtime>10;
脚本主入口
if__name__=='__main__':
#每5秒执行检查任务
schedule.every(5).seconds.do(kill_slow)
#此处固定写法,意思是每秒钟schedule看下是否有pending的任务,有就执行
whileTrue:
schedule.run_pending()
time.sleep(1)
schedule的其它示例
importschedule
importtime
defjob(message='stuff'):
print("I'mworkingon:",message)
#每10分钟
schedule.every(10).minutes.do(job)
#每小时
schedule.every().hour.do(job,message='things')
#每天10点30分
schedule.every().day.at("10:30").do(job)
whileTrue:
schedule.run_pending()
time.sleep(1)
pymysql使用
#连接数据库,设置结果集用dict返回,autocommit自动提交事务 db=pymysql.connect(host='localhost',db='dbname', user='root',passwd='admin', port=3306,charset='utf8', cursorclass=pymysql.cursors.DictCursor,autocommit=True) cursor=db.cursor()
查询符合条件的慢会话并结束
defkill_slow():
cursor.execute(
"""
SELECT
id,
info,
time
FROM
information_schema.`PROCESSLIST`
WHERE
infoLIKE'%select*fromtable%'
ANDtime>10;
""")
slow_sessions=cursor.fetchall()
forslow_sessioninslow_sessions:
print("slowsessiondetected,killit:\nid:%s\nsql:%s"%(
slow_session[0],slow_session[1]))
cursor.execute("kill%s",slow_session[0])
完整代码
importtime
importpymysql
importschedule
#连接数据库,设置结果集用dict返回,autocommit自动提交事务
db=pymysql.connect(host='localhost',db='dbname',
user='root',passwd='admin',
port=3306,charset='utf8',
cursorclass=pymysql.cursors.DictCursor,autocommit=True)
cursor=db.cursor()
defkill_slow():
cursor.execute(
"""
SELECT
id,
info,
time
FROM
information_schema.`PROCESSLIST`
WHERE
infoLIKE'%select*fromtable%'
ANDtime>10;
""")
slow_sessions=cursor.fetchall()
forslow_sessioninslow_sessions:
print("slowsessiondetected,killit:\nid:%s\nsql:%s"%(
slow_session[0],slow_session[1]))
cursor.execute("kill%s",slow_session[0])
if__name__=='__main__':
#每5秒执行检查任务
schedule.every(5).seconds.do(kill_slow)
#此处固定写法,意思是每秒钟schedule看下是否有pending的任务,有就执行
whileTrue:
schedule.run_pending()
time.sleep(1)
总结
以上所述是小编给大家介绍的python自动结束mysql慢查询会话的实例代码,希望对大家有所帮助!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。