[内容] MariaDB & MySQL 大量连接数和高消耗 SQL 语句的临时处理

内容一:数据库连接数处理

1.1 查看数据库连接数

1.1.1 查看已设置的最大连接数
mysql> show variables like 'max_connections';

或者:

mysql> show variables like '%connect%';
1.1.2 查看试图连接数
mysql> show status like '%connect%';
1.1.3 查看目前的连接数
mysql> show status like 'Threads_connected';

或者:

mysql> show status where variable_name = 'Threads_connected';

1.2 需改数据库最大连接数

1.2.1 修改 /etc/my.cnf 配置文件
# vi /etc/my.cnf

添加以下内容:

......
max_connections=32000
1.2.2 重启 MySQL 数据库

(步骤略)

内容二:高消耗 SQL 语句处理

2.1 查看被锁住的表

mysql> select * from information_schema.innodb_trx where trx_state='LOCK WAIT';

(补充:可以通过被锁住的表推断哪些 SQL 语句耗时较长)

2.2 查看 SQL 语句

2.2.1 查看所有的 SQL 语句
mysql> show processlist
2.2.2 查看所有的 SQL 语句并按照耗时长短排序
mysql> select id,user,host,state,info,time,command 
  from information_schema.processlist 
  where command !='Sleep'
  order by time desc;


补充:
1) 这里以显示 information_schema.processlist 表里的 id、user、host、state、info、time、command 字段为例
2) 这里的 where command != ‘Sleep’ 代表排除处于睡眠状态的 SQL 语句

2.2.3 查看耗时最高的 10 条 SQL 语句并按照耗时长短排序
mysql> select *
from information_schema.processlist
where command != 'Sleep'
  and time > 0 
order by time desc
limit 10;


补充:
1) 这里以显示 information_schema.processlist 表里的所有字段为例
2) 这里的 where command != ‘Sleep’ 代表排除处于睡眠状态的 SQL 语句

2.2.4 查看对某个数据库进行操作的耗时最高的 10 条 SQL 语句
mysql> select id,user,host,state,info,time,command 
  from information_schema.processlist 
  -- where db = 'eternalcenter'
  where command !='Sleep'
  order by time desc;


补充:
1) 这里以显示 information_schema.processlist 表里的 id、user、host、state、info、time、command 字段为例
2) 这里的 — where db = ‘eternalcenter’ 代表查看对 eternalcenter 库进行操作的 SQL 语句
3) 这里的 where command != ‘Sleep’ 代表排除处于睡眠状态的 SQL 语句

2.3 杀死高消耗的 SQL 语句

2.3.1 杀死某条 SQL 语句
mysql> kill <SQL ID>
2.3.2 杀死正在运行的耗时最高的 5 条 SQL 语句
mysql> select concat('kill ',id,';')
from information_schema.processlist
where command ='Query' 
order by time desc
limit 5;
2.3.3 确认正在运行的耗时最高的 5 条 SQL 语句被杀死
mysql> select ID,COMMAND,INFO 
from information_schema.processlist
where command ='Query' 
order by time desc
;