MySQL维护之连接数、线程等
实际生产维护中可能还会查看如下内容:
1、如何在MySQL中查询OS线程id(LWP轻量级线程)?
OS系统提供ps -Lf pid命令查看LWP;在performance_schema.threads中有一列thread_os_id,可以通过该列匹配到OS线程id。具体如下所示:
select a.thread_id, a.processlist_id, a.processlist_user, a.processlist_time, a.connection_type, a.thread_os_id from performance_schema.threads a where a.type='FOREGROUD' and a.thread_os_id=2136;
当前查询肯定是没有数据的,因为当前环境中没有任何使用数据——仅演示具体操作。
2、如何查看MySQL的连接数?
查看当前连接数就是查看Threads,通过命令mysqladmin -u root -plhr -h ... status可以获得,如下:
说明当前有3个FOREGROUD类型的连接。当然有可以通过上述performance_schema.threads或show processlist查询。
3、如何杀掉某个MySQL客户端连接或正在执行的SQL语句?
可以使用OS提供的kill命令,关键是得找到该SQL对应的pid。具体执行如下:kill [connection|query] thread_id
1)show processlist语句查看哪些线程正在运行;
2)kill thread_id。
需要注意的是:kill connection会终止与给定thread_id有关的连接,而kill query仅会终止当前正在执行的语句(即连接状态还是原态)。默认是connection方式kill。
4、profile的意义及使用场景
MySQL 可以使用profile分析SQL语句的性能消耗情况。比如:查询到SQL会执行多少时间并看出CPU、内存使用量,执行过程中系统锁及表锁的花费时间等信息。
通过have_profiling参数可以查看M有SQL是否支持profile,通过profiling参数可以查看当前系统profile是否开启show variables like '%profil%'。
有关profile的一些常用命令如下:
set profiling = 1;:基于会话级别开启,关闭则使用set profiling = off。
show profile cpu for query 1;:查看CPU的消耗情况。
show profile memory for query 1;:查看内存消耗情况。
show profile block io, cpu for query 1;:查看I/O及CPU的消耗情况。
可以使用如下的语句查询SQL的整体消耗百分比:
select state sum(duration) as total_r,
round(100*sum(duration))/(select sum(duration) from information_schema.profiling where query_id=1) as pct_r,
count(*) as calls, sum(duration)/count(*) as "R/Call"
from information_schema.profiling
where query_id = 1 group by state order by toatl_r desc;