運維筆記--postgresql占用CPU問題定位


運維筆記--postgresql占用CPU問題定位

場景描述:

 業務系統訪問變慢,登陸服務器查看系統負載並不高,然后查看占用CPU較高的進程,發現是連接數據庫的幾個進程占用系統資源較多。

處理方式:

查找出占用系統內存&CPU排名前10的進程:[或者用top命令查看]  ---這里需要注意,如果用了容器,需要進入容器內部查看相應的進程。

ps aux|head -1;ps aux|grep -v PID|sort -rn -k +3|head

切換到postgres用戶,執行psql,進入數據庫終端:指定上述命令找到的系統進程號

SELECT procpid, START, now() - START AS lap, current_query  FROM ( 
    SELECT backendid, pg_stat_get_backend_pid (S.backendid) AS procpid,
    pg_stat_get_backend_activity_start (S.backendid) AS START,pg_stat_get_backend_activity (S.backendid) AS current_query  
FROM (SELECT pg_stat_get_backend_idset () AS backendid) AS S) AS S 
    WHERE current_query <> '<IDLE>' and procpid=15874
ORDER BY lap DESC;

定位到SQL,確認該SQL完成的業務查詢功能,查看執行計划,增加索引or 修改代碼。

SELECT "******_edoc_queue".id 
    FROM "******_edoc_queue" 
        WHERE (("*******_edoc_queue"."edoc_id" = '521300000004TCS60515001FV-960157.pdf')  
        AND  ("*****_edoc_queue"."active" = true)) 
        ORDER BY "*****_edoc_queue"."id"

 查詢該條SQL的執行計划:(Postgresql使用explain analyze + sql語法的格式)

postgres=# \c ***你的實際模式schema
You are now connected to database "stbg" as user "postgres".
stbg=# explain analyze SELECT "cus_center_new_edoc_queue".id FROM "cus_center_new_edoc_queue" WHERE (("cus_center_new_edoc_queue"."edoc_id" = '521300000008TCS60417066FV-960101.pdf')  AND  ("cus_center_new_edoc_queue"."active" = true)) ORDER BY "cus_center_new_edoc_queue"."id";

---得到如下執行計划:
stbg= BY "cus_center_new_edoc_queue"."id";ter_new_edoc_queue"."active" = true)) ORDER QUERY PLAN         -----------------------------------------------------------------------------
Sort  (cost=21044.85..21044.85 rows=1 width=4) (actual time=109.905..109.905 ro
ws=0 loops=1)
   Sort Key: id
   Sort Method: quicksort  Memory: 25kB
   ->  Seq Scan on cus_center_new_edoc_queue  (cost=0.00..21044.84 rows=1 width=4) (actual time=109.880..109.880 rows=0 loops=1)
         Filter: (active AND ((edoc_id)::text = '521300000008TCS60417066FV-960101.pdf'::text))
         Rows Removed by Filter: 583348
 Planning time: 0.468 ms
 Execution time: 109.952 ms
(8 rows)

----可以看出執行查詢時間:109.952 ms

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM