MySQL占用CPU超過百分之100解決過程

2022-08-09 02:15:17 字數 2195 閱讀 9982

本文**自:

訪問網頁504 gateway time-out,登陸伺服器檢視,記憶體正常,cpu使用率達到了400%,因為是4核,所以到了400%,幾乎全部滿負載在跑了,又在下圖中發現,單單乙個mysqld的程序,就佔了390%,毫無疑問,資料庫的問題導致了網頁504。

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

2、登陸資料庫,輸入show full processlist;可以看到正在執行的語句

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負載很輕,頁面恢復正常

cpu 占用百分之五十

include include include include include include using namespace std define us per ms 1000 define ms per sec 1000 define speed 60000000ul void thread i...

H 遇到百分之百的女孩

火車要開了,女孩一直目送那個男孩的離開,一步,兩步,直到男孩踏上車都沒有回過頭看女孩一眼。火車開了,女孩淚如雨下 我一直在等他回頭,只要一眼,我就跟隨他去。車上,男孩看著急速倒退的風景心口隱隱作痛 為什麼你不叫我一聲,只要一聲,我就為你留下 現在時光老人走在你的面前,對你說,如果你能回答我乙個問題,...

食品部銷售後百分之十

insert into wyl spbl select n5001,n5002,n5004,n5019,n5011,flje,flpm flsl pmbl,flpm,flsl from select n5001,n5002,n5004,n5019,n5011,sum n5011 over parti...