ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

mysql占用CPU超过100%解决过程

2019-06-20 11:02:04  阅读:284  来源: 互联网

标签:posttime 100% top CPU most catalog mysql id desc


2017年12月2日上午,将学校新闻网2015年之前的45000多条记录迁移到了新网站的mysql数据库,新网站上有2015年1月1日之后的9000多条记录,数据量一下子增加了5倍。
2017年12月3日晚上9点多,有领导和老师反映新闻网无法访问,立即登录服务器进行排查。

一、使用top命令看到的情况如下:

可以看到服务器负载很高,,mysql CPU使用已达到接近400%(因为是四核,所以会有超过100%的情况)。

二、在服务器上执行mysql -u root -p之后,输入show full processlist; 可以看到正在执行的语句。

可以看到是下面的SQL语句执行耗费了较长时间。
SELECT id,title,most_top,view_count,posttime FROM article 
where status=3 AND catalog_id in (select catalog_id from catalog where catalog_id=17 or parent_id=17)  
order by most_top desc,posttime desc limit 0,8
但是从数据库设计方面来说,该做的索引都已经做了,SQL语句似乎没有优化的空间。
直接执行此条SQL,发现速度很慢,需要1-6秒的时间(跟mysql正在并发执行的查询有关,如果没有并发的,需要1秒多)。如果把排序依据改为一个,则查询时间可以缩短至0.01秒(most_top)或者0.001秒(posttime)。

三、修改mysql配置文件中的pool/buffer等数值,重启mysql都没有作用。

四、通过EXPLAIN分析SQL语句
EXPLAIN SELECT id,title,most_top,view_count,posttime FROM article 
where status=3 AND catalog_id in (select catalog_id from catalog where catalog_id=17 or parent_id=17)  
order by most_top desc,posttime desc limit 0,8

可以看到,主select对27928条记录使用filesort进行了排序,这是造成查询速度慢的原因。然后8个并发的查询使CPU专用很高。

五、优化
首先是缩减查询范围
SELECT id,title,most_top,view_count,posttime FROM article 
where status=3 AND catalog_id in (select catalog_id from catalog where catalog_id=17 or parent_id=17)  and DATEDIFF(NOW(),posttime)<=90
order by most_top desc,posttime desc limit 0,8
发现有一定效果,但效果不明显,原因是每条记录都要做一次DATEDIFF运算。后改为
SELECT id,title,most_top,view_count,posttime FROM article 
where status=3 AND catalog_id in (select catalog_id from catalog where catalog_id=17 or parent_id=17)  and postime>='2017-09-05'
order by most_top desc,posttime desc limit 0,8
查询速度大幅提高。在PHP中,日期阈值通过计算得到
$d = date("Y-m-d", strtotime('-90 day'));
$sql = "
SELECT id,title,most_top,view_count,posttime FROM article 
where status=3 AND catalog_id in (select catalog_id from catalog where catalog_id=17 or parent_id=17)  and postime>='$d'
order by most_top desc,posttime desc limit 0,8
"

六、效果
查询时间大幅度缩短,CPU负载很轻


---------------------
作者:jimshen
来源:CSDN
原文:https://blog.csdn.net/jimshen/article/details/78706538
版权声明:本文为博主原创文章,转载请附上博文链接!

标签:posttime,100%,top,CPU,most,catalog,mysql,id,desc
来源: https://www.cnblogs.com/wcm19910616/p/11057446.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有