码迷,mamicode.com
首页 > 数据库 > 详细

MySQL管理长时间运行查询

时间:2018-03-29 17:27:59      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:长查询

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

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

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

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


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

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

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

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


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

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

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

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


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;


MySQL管理长时间运行查询

标签:长查询

原文地址:http://blog.51cto.com/395469372/2092587

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!