首页 技术 正文
技术 2022年11月12日
0 收藏 586 点赞 3,977 浏览 1449 个字

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

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

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

2、登陆数据库,输入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

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

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

可以看到,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负载很轻,页面恢复正常

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,085
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,560
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,409
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,182
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,819
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,902