MySQL管理长时间运行查询

1. 出现长时间执行的查询的缘由sql

   因为SQL执行效率差而致使的长时间查询:ide

   因为被SQL注入而致使的长时间查询:测试

   因为DDL语句引发表元数据锁等待:fetch


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

    一般来讲,除非是BI/报表类查询,不然长时间执行的查询对于应用缺少意义。orm

    消耗系统资源,好比大量长时间查询可能会引发 CPU、IOPS 和/或 链接数 使用率太高等问题。索引

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


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

应用方面应注意增长防止 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;
相关文章
相关标签/搜索