MySQL占用CPU超过百分之100解决过程

本文转载自: https://www.93bok.com

访问网页504 Gateway Time-out,登陆服务器查看,内存正常,CPU使用率达到了400%,因为是4核,所以到了400%,几乎全部满负载在跑了,又在下图中发现,单单一个mysqld的进程,就占了390%,毫无疑问,数据库的问题导致了网页504。

1、使用top看到的情况如下

isoa7D.png

2、登陆数据库,输入show full processlist;可以看到正在执行的语句

isowAe.png

可以看到是下面的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

还可以从show full processlist命令中得出下图中的端口号,我们也可以使用netstat -anupt | grep 端口号查看一下是什么进程打开的这个MySQL连接,这里我就不演示了,你们可以自己尝试排查一下问题。

isor9A.png

3、但是从数据库设计方面来说,该做的索引都已经做了,SQL语句似乎没有优化的空间。

直接执行此条SQL,发现速度很慢,需要7-8秒的时间(跟mysql正在并发执行的查询有关,如果没有并发的,需要1秒多)。如果把排序依据改为一个,则查询时间可以缩短至0.01秒(most_top)或者0.001秒(posttime)。

4、通过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

iso6jP.md.png

可以看到,select对45万条记录使用filesort进行排序,这是造成查询速度慢的原因。

5、优化

首先是缩减查询范围

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

查询速度大幅提高。

6、效果

查询时间大幅度缩减,CPU负载很轻,页面恢复正常

iso2B8.png

iso4hj.png

原文地址:https://www.cnblogs.com/93bok/p/12425187.html