MySQL管理长时间运行查询

  1. 出现长时间执行的查询的原因

    由于SQL执行效率差而导致的长时间查询:

    由于被SQL注入而导致的长时间查询:

    由于DDL语句引起表元数据锁等待:

  2. 长时间执行的查询带来的问题

    通常来说,除非是BI/报表类查询,否则长时间执行的查询对于应用缺乏意义。

    消耗系统资源,比如大量长时间查询可能会引起 CPU、IOPS 和/或 连接数 使用率过高等问题。

    带来系统不稳定的隐患(比如 InnoDB 引擎表上的长时间查询可能会导致 ibdata1 系统文件尺寸的增加)

  3. 如何避免长时间执行的查询

    应用方面应注意增加防止 SQL 注入的保护。

    在新功能模块上线前,进行压力测试,避免出现执行效率很差的 SQL 大量执行的情况。

    扫描二维码关注公众号,回复: 7447442 查看本文章

    尽量在业务低峰期进行索引创建删除、表结构修改、表维护和表删除操作。

  4. 如何处理长时间执行的查询

a、通过命令 show processlist; 查看当前执行会话,Kill会话长时间查询。

b、创建事件自动清理长时间执行的查询

create event my_long_running_query_monitor
on schedule every 5 minute
starts '2018-08-08 11:00:00'
on completion preserve enable do
begin
declare v_sql varchar(500);
declare no_more_long_running_query integer default 0;
declare c_tid cursor for
select concat ('kill ',id,';') from
information_schema.processlist
where time >= 3600
and user = substring(current_user(),1,instr(current_user(),'@')-1)
and command not in ('sleep')
and state not like ('waiting for table%lock');
declare continue handler for not found
set no_more_long_running_query=1;

open c_tid;
repeat
fetch c_tid into v_sql;
set @v_sql=v_sql;
prepare stmt from @v_sql;
execute stmt;
deallocate prepare stmt;
until no_more_long_running_query end repeat;
close c_tid;
end;

猜你喜欢

转载自blog.51cto.com/14555883/2441094