mysqlCPU超过100%的详细解决过程

前段时间我的一个网站经常打不开,通过检查发现服务器cpu占用超过100%,通过top命令发现是mysql占用cpu特别高导致的,下面这篇文章主要给大家介绍了关于mysql占用CPU超过100%的详细解决过程,需要的朋友可以参考下

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

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

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

可以看到是下面的SQL语句执行耗费了较长时间。

1

2

3

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语句

1

2

3

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专用很高。

五、优化

首先是缩减查询范围

1

2

3

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运算。后改为

1

2

3

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中,日期阈值通过计算得到

1

2

3

4

5

6

$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负载很轻

以上就是mysql占用CPU超过100%的详细解决过程的详细内容。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值