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

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

場景描述:數據庫

 業務系統訪問變慢,登錄服務器查看系統負載並不高,而後查看佔用CPU較高的進程,發現是鏈接數據庫的幾個進程佔用系統資源較多。服務器

處理方式:運維

查找出佔用系統內存&CPU排名前10的進程:[或者用top命令查看]  ---這裏須要注意,若是用了容器,須要進入容器內部查看相應的進程。oop

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

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

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 修改代碼。ui

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語法的格式)spa

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
相關文章
相關標籤/搜索