Python自动终止MySQL慢查询会话的脚本实现

沿途有光
沿途有光
发布时间:2026-10-11 | 3人浏览过
原创

本文介绍如何使用Python脚本自动检测并终止MySQL数据库中的慢查询会话。通过pymysql连接数据库,利用information_schema.processlist筛选耗时超过阈值的会话,并结合schedule库实现定时任务调度,自动执行kill命令释放资源。

慢查询处理原理

MySQL中的慢查询通常由复杂的SQL语句、数据表过大、索引缺失或查询逻辑低效引起。为了保障数据库性能,可以通过脚本定期检测并结束符合条件的慢查询会话。该方案主要涉及以下技术点:查询MySQL慢查询会话、使用schedule库进行定时任务调度,以及通过pymysql执行SQL语句。

查询慢查询会话

在MySQL中,可以使用`SHOW PROCESSLIST;`查看所有会话,但该命令不支持按条件过滤。为了精准定位慢查询,建议从`information_schema`库中查询会话信息,这样可以按条件过滤。例如,查询正在执行特定SQL且持续时间超过10秒的会话:

SELECT
  id,
  info,
  time
FROM
  information_schema.`PROCESSLIST`
WHERE
  info LIKE '%select * from table%'
AND time > 10;

此外,可以直接拼接`KILL`命令,将结果拷贝到控制台执行:

SELECT
  concat('KILL ', id, ';')
FROM
  information_schema.`PROCESSLIST`
WHERE
  info LIKE '%select * from table%'
AND time > 10;

Python实现自动杀进程

使用Python的`pymysql`库连接MySQL数据库,并设置结果集以字典形式返回,同时开启自动提交事务:

# 连接数据库,设置结果集用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()

定义`kill_slow`函数,用于查询并终止慢查询会话:

def kill_slow():
  cursor.execute(
    """
    SELECT
      id,
      info,
      time
    FROM
      information_schema.`PROCESSLIST`
    WHERE
      info LIKE '%select * from table%'
    AND time > 10;
    """)
  slow_sessions = cursor.fetchall()
  for slow_session in slow_sessions:
    print("slow session detected, kill it:\n id:%s\nsql:%s" % (
      slow_session[0], slow_session[1]))
    cursor.execute("kill %s", slow_session[0])

定时任务调度

使用`schedule`库实现定时任务调度,每隔5秒执行一次`kill_slow`函数:

import time
import pymysql
import schedule
# 连接数据库,设置结果集用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()
def kill_slow():
  cursor.execute(
    """
    SELECT
      id,
      info,
      time
    FROM
      information_schema.`PROCESSLIST`
    WHERE
      info LIKE '%select * from table%'
    AND time > 10;
    """)
  slow_sessions = cursor.fetchall()
  for slow_session in slow_sessions:
    print("slow session detected, kill it:\n id:%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的任务,有就执行
  while True:
    schedule.run_pending()
    time.sleep(1)

此外,`schedule`库还支持其他定时任务示例:

import schedule
import time
def job(message='stuff'):
 print("I'm working on:", 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)
while True:
 schedule.run_pending()
 time.sleep(1)

以上就是Python自动结束MySQL慢查询会话的详细内容,更多关于Python、MySQL、慢查询、自动杀进程、pymysql、schedule的资料请关注本站其它相关文章!

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表