在 MySQL 数据库的日常管理和优化中,进程管理是一项重要的任务。通过监控和适时地终止异常或低效的数据库连接和查询,可以显著提升系统的性能和稳定性。下面介绍几种常见的 MySQL 进程管理场景及相应的处理策略。
手动获取PROCESSLIST方式
获取示例
#查询某个用户的所有线程
SELECT concat( 'KILL ', id, ';' ) FROM information_schema.PROCESSLIST WHERE User LIKE 'carduser';
#查询某个IP的线程
SELECT concat( 'KILL ', id, ';' ) FROM information_schema.PROCESSLIST WHERE Host LIKE '172.16.16.10%';
#列出所有状态为 "Sending data" 的进程
SELECT concat( 'KILL ', id, ';' ) FROM information_schema.PROCESSLIST WHERE STATE LIKE 'Sending data';
#查找所有执行时间超过100秒的查询(TIME > 100),并且其命令类型是 Query 的进程
SELECT concat( 'KILL ', id, ';' ) FROM information_schema.`PROCESSLIST` WHERE Command = 'Query' AND TIME > 100;
#查找处于空闲(即 Sleep 状态)超过500秒的连接
SELECT concat( 'KILL ', id, ';' ) FROM information_schema.`PROCESSLIST` WHERE Command = 'Sleep' AND TIME > 500;
#查询是针对特定表 mp_sms_send_record 上的更新操作
SELECT concat( 'KILL ', id, ';' ) FROM information_schema.`PROCESSLIST` WHERE Command = 'Execute' AND Info LIKE "update `mp_sms_send_record`%";
PT-KILL方式
操作示例
#kill执行时间超过500秒事务
pt-kill --host=192.0.0.1 --user=root --password=123456 --busy-time 500 --match-command Query --victims all --daemonize --kill --interval 10 --log=sql.log
#print执行时间超过500秒事务
pt-kill --host=192.0.0.1 --user=root --password=123456 --busy-time 500 --match-command Query --victims all --daemonize --print --log=sql.log
#kill某个用户的事务
pt-kill --host=192.0.0.1 --user=root --password=123456 --match-user=webuser --match-command Query --victims all --daemonize --kill --interval 10 --log=sql.log
#kill并print出指定的select语句
pt-kill --host=192.0.0.1 --user=root --password=123456 --interval=5 --match-info=select t1.sf_id, t1.company_id, t1.all_count, t1.now_count, t1.update_time, t2.third_name from el_ks_sop t1 left join el_third_auth_bind t2 on t1.third_key = t2.third_id WHERE t1.status = 1 and t2.use_status = 1 order by sf_id limit 1 --print --daemonize --kill
参数介绍
--match-all
--match-command
--match-db
--match-host
--match-info 匹配杀掉SELECT|INSERT|UPDATE语句
--match-state 匹配杀掉的状态
--match-user 匹配杀掉的用户
--busy-time SQL已执行时间
--daemonize 后台运行
--interval 每隔多久检查一次
--victims all #all kill该类中所有的查询;oldest 只kill最旧的单个查询;all-but-oldest 除了就得查询外,其他的都kill
通过对 MySQL 进程的有效管理,不仅可以改善数据库的整体性能,还能提高系统的稳定性和可靠性。然而,在实际应用上述策略时,必须谨慎行事,并充分考虑每个决策可能带来的后果。通常建议先进行一段时间的监控,了解系统的行为模式后,再采取适当的行动。此外,优化查询逻辑和应用程序代码也是解决问题的根本方法之一。
如果您觉得这篇帖子对您有所帮助,别忘了点击关注、点赞支持我们!同时也欢迎大家多多转发,让更多人看到,感谢大家的支持与鼓励!