如何快速定位到影响mysql cpu飙升的原因——筑梦之路

2024-06-04 00:12

本文主要是介绍如何快速定位到影响mysql cpu飙升的原因——筑梦之路,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

  通常我们只需要执行show processlist 进行查看,一般执行时间最长的SQL八九不离十就是罪魁祸首,但当show processlist的输出有近千条,那么很难第一眼就发现有问题的SQL,那么如何快速找到呢?其实也非常简单。我们知道mysqld是单进程多线程。那么我们可以使用top获取mysqld进程的各个线程的cpu使用情况。

top -H -p mysqld_pid

测试sql:

select * from cpu_h order by rand() limit 1;

可以看到是线程22682占用cpu比较高,接着通过查看performance_schema.threads表,找到相关SQL

select * from performance_schema.threads where thread_os_id=22682

再通过show processlist看

 找到processlist id以后,就可以直接使用命令kill。

python脚本:

(统计活跃线程SQL执行的次数)

#!/usr/bin/python# -*- coding:utf-8 -*-import argparseimport MySQLdbimport argparseimport commandsimport sysimport MySQLdb.cursorsfrom warnings import filterwarningsfrom warnings import resetwarningsfilterwarnings('ignore', category = MySQLdb.Warning)reload(sys)sys.setdefaultencoding('utf8')def init_parse():parser = argparse.ArgumentParser(epilog='by yayun @2022',)parser.add_argument('-n','--num',required=False,default=1,help='获取多少条最耗费cpu的记录,默认1条')parser.add_argument('-a','--active',action='store_true',default=False,help='统计活跃线程各类SQL的条目数')return parserdef mysql_exec(sql):try:   conn=MySQLdb.connect(host='127.0.0.1',user='root',passwd='xx',port=3306,connect_timeout=15,charset='utf8')curs = conn.cursor()curs.execute(sql)conn.commit()curs.close()conn.close()except Exception,e:print "mysql execute: " + str(e)def mysql_query(sql):conn=MySQLdb.connect(host='127.0.0.1',user='root',passwd='xx',port=3306,connect_timeout=15,charset='utf8',cursorclass = MySQLdb.cursors.DictCursor)cursor = conn.cursor()count=cursor.execute(sql)if count == 0 :result=0else:result=cursor.fetchall()return resultcursor.close()conn.close()if __name__ == '__main__':parser = init_parse()args = parser.parse_args()slow_sql_numbers=args.numactive_thread_status=args.activemysqld_pid = commands.getoutput("cat /data/mysql/3306/pid_mysql.pid")get_mysql_thead_cmd="top -H -p %s  -n 1 | grep mysqld | head -n %s | awk '{print $1,$2}' | sed 's/mysql//g'" % (mysqld_pid,slow_sql_numbers)tmp_mysqld_thread=commands.getoutput(get_mysql_thead_cmd).split()mysqld_thread=[]for i in tmp_mysqld_thread:try:a=i.replace('\x1b[0;10m\x1b[0;10m','')a=i.replace('\x1b[0;10m','')mysqld_thread.append(int(a))except Exception,e:passactive_thread_sql="select  * from ( select max(user) as user,max(db) as db , max(info) as runningsql,count(*) as rungingsql_cnt from information_schema.processlist where db is not null  and info is not null and info like '%SELECT%' group by user, db, md5(info)   union all     select max(user) as user,max(db) as db ,max(info) as runningsql,count(*) as rungingsql_cnt from information_schema.processlist where db is not null  and info is not null and info like 'UPDATE%' group by user, db,md5(info)  ) a order by 4 desc limit 10"if active_thread_status:resut=mysql_query(active_thread_sql)if resut:for i in resut:print "运行条目统计: %s | 运行SQL: %s  | 运行用户:%s " % (i['rungingsql_cnt'],i['runningsql'],i['user'])print "============================================="    processlist_id=[]if len(mysqld_thread) >= 2:new_mysqld_thread=tuple(mysqld_thread)get_slow_sql="select PROCESSLIST_ID,PROCESSLIST_USER,PROCESSLIST_HOST,\PROCESSLIST_DB,PROCESSLIST_TIME,PROCESSLIST_INFO from performance_schema.threads where thread_os_id in %s" % (new_mysqld_thread,)else:new_mysqld_thread=mysqld_threadget_slow_sql="select PROCESSLIST_ID,PROCESSLIST_USER,PROCESSLIST_HOST,\PROCESSLIST_DB,PROCESSLIST_TIME,PROCESSLIST_INFO from performance_schema.threads where thread_os_id=%s" % (new_mysqld_thread[0])new_resut=mysql_query(get_slow_sql)for b in new_resut:if b['PROCESSLIST_ID']:processlist_id.append(b['PROCESSLIST_ID'])if b['PROCESSLIST_INFO'] != None:print "SQL已运行时间: %s秒|执行SQL用户: %s |执行SQL来源ip: %s |操作的库: %s |SQL详情: %s |PROCESSLIST ID: %s" % (b['PROCESSLIST_TIME'],b['PROCESSLIST_USER'],b['PROCESSLIST_HOST'],b['PROCESSLIST_DB'],b['PROCESSLIST_INFO'],b['PROCESSLIST_ID'])if processlist_id:print "============================================="print "以上耗费CPU资源的SQL是否需要杀掉? 请输入Y/N"while True:in_content = raw_input("请输入:")if in_content == "Y":for p in processlist_id:sql="kill %s" % (p) mysql_exec(sql)exit(0)elif in_content == "N":print("退出程序!")exit(0)else:print("输入有误,请重输入!")

搜集来自:如何快速找到影响MySQL CPU升高的原因

这篇关于如何快速定位到影响mysql cpu飙升的原因——筑梦之路的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1028514

相关文章

MySQL的JDBC编程详解

《MySQL的JDBC编程详解》:本文主要介绍MySQL的JDBC编程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录前言一、前置知识1. 引入依赖2. 认识 url二、JDBC 操作流程1. JDBC 的写操作2. JDBC 的读操作总结前言本文介绍了mysq

java.sql.SQLTransientConnectionException连接超时异常原因及解决方案

《java.sql.SQLTransientConnectionException连接超时异常原因及解决方案》:本文主要介绍java.sql.SQLTransientConnectionExcep... 目录一、引言二、异常信息分析三、可能的原因3.1 连接池配置不合理3.2 数据库负载过高3.3 连接泄漏

Linux下MySQL数据库定时备份脚本与Crontab配置教学

《Linux下MySQL数据库定时备份脚本与Crontab配置教学》在生产环境中,数据库是核心资产之一,定期备份数据库可以有效防止意外数据丢失,本文将分享一份MySQL定时备份脚本,并讲解如何通过cr... 目录备份脚本详解脚本功能说明授权与可执行权限使用 Crontab 定时执行编辑 Crontab添加定

MySQL中On duplicate key update的实现示例

《MySQL中Onduplicatekeyupdate的实现示例》ONDUPLICATEKEYUPDATE是一种MySQL的语法,它在插入新数据时,如果遇到唯一键冲突,则会执行更新操作,而不是抛... 目录1/ ON DUPLICATE KEY UPDATE的简介2/ ON DUPLICATE KEY UP

MySQL分库分表的实践示例

《MySQL分库分表的实践示例》MySQL分库分表适用于数据量大或并发压力高的场景,核心技术包括水平/垂直分片和分库,需应对分布式事务、跨库查询等挑战,通过中间件和解决方案实现,最佳实践为合理策略、备... 目录一、分库分表的触发条件1.1 数据量阈值1.2 并发压力二、分库分表的核心技术模块2.1 水平分

Python与MySQL实现数据库实时同步的详细步骤

《Python与MySQL实现数据库实时同步的详细步骤》在日常开发中,数据同步是一项常见的需求,本篇文章将使用Python和MySQL来实现数据库实时同步,我们将围绕数据变更捕获、数据处理和数据写入这... 目录前言摘要概述:数据同步方案1. 基本思路2. mysql Binlog 简介实现步骤与代码示例1

sysmain服务可以禁用吗? 电脑sysmain服务关闭后的影响与操作指南

《sysmain服务可以禁用吗?电脑sysmain服务关闭后的影响与操作指南》在Windows系统中,SysMain服务(原名Superfetch)作为一个旨在提升系统性能的关键组件,一直备受用户关... 在使用 Windows 系统时,有时候真有点像在「开盲盒」。全新安装系统后的「默认设置」,往往并不尽编

使用shardingsphere实现mysql数据库分片方式

《使用shardingsphere实现mysql数据库分片方式》本文介绍如何使用ShardingSphere-JDBC在SpringBoot中实现MySQL水平分库,涵盖分片策略、路由算法及零侵入配置... 目录一、ShardingSphere 简介1.1 对比1.2 核心概念1.3 Sharding-Sp

深度剖析SpringBoot日志性能提升的原因与解决

《深度剖析SpringBoot日志性能提升的原因与解决》日志记录本该是辅助工具,却为何成了性能瓶颈,SpringBoot如何用代码彻底破解日志导致的高延迟问题,感兴趣的小伙伴可以跟随小编一起学习一下... 目录前言第一章:日志性能陷阱的底层原理1.1 日志级别的“双刃剑”效应1.2 同步日志的“吞吐量杀手”

MySQL 表空却 ibd 文件过大的问题及解决方法

《MySQL表空却ibd文件过大的问题及解决方法》本文给大家介绍MySQL表空却ibd文件过大的问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考... 目录一、问题背景:表空却 “吃满” 磁盘的怪事二、问题复现:一步步编程还原异常场景1. 准备测试源表与数据