查找和殺掉postgresql堵塞的會話
1.創(chuàng)建視圖,可以隨時使用:
CREATE VIEW pg_blocking AS SELECT
blocked_locks.pid AS blocked_pid,
blocked_activity.usename AS blocked_user,
blocking_locks.pid AS blocking_pid,
blocking_activity.usename AS blocking_user,
blocked_activity. QUERY AS blocked_statement,
blocking_activity. QUERY AS current_statement_in_blocking_process
FROM
pg_catalog.pg_locks blocked_locks
JOIN pg_catalog.pg_stat_activity blocked_activity ON blocked_activity.pid = blocked_locks.pid
JOIN pg_catalog.pg_locks blocking_locks ON blocking_locks.locktype = blocked_locks.locktype
AND blocking_locks. DATABASE IS NOT DISTINCT
FROM
blocked_locks. DATABASE
AND blocking_locks.relation IS NOT DISTINCT
FROM
blocked_locks.relation
AND blocking_locks.page IS NOT DISTINCT
FROM
blocked_locks.page
AND blocking_locks.tuple IS NOT DISTINCT
FROM
blocked_locks.tuple
AND blocking_locks.virtualxid IS NOT DISTINCT
FROM
blocked_locks.virtualxid
AND blocking_locks.transactionid IS NOT DISTINCT
FROM
blocked_locks.transactionid
AND blocking_locks.classid IS NOT DISTINCT
FROM
blocked_locks.classid
AND blocking_locks.objid IS NOT DISTINCT
FROM
blocked_locks.objid
AND blocking_locks.objsubid IS NOT DISTINCT
FROM
blocked_locks.objsubid
AND blocking_locks.pid != blocked_locks.pid
JOIN pg_catalog.pg_stat_activity blocking_activity ON blocking_activity.pid = blocking_locks.pid
WHERE
NOT blocked_locks.GRANTED;
查詢創(chuàng)建的視圖查詢堵塞:
select * from pg_blocking;
2.殺掉查出的阻塞會話:
kill有兩種方式,第一種是:
SELECT pg_cancel_backend(PID); ###取消一個正在執(zhí)行的SQL;
第二種是:
SELECT pg_terminate_backend(PID); ###終止一個后臺服務(wù)進程,同時釋放此后臺服務(wù)進程的資源。
成都創(chuàng)新互聯(lián)公司是一家專注網(wǎng)站建設(shè)、網(wǎng)絡(luò)營銷策劃、微信小程序、電子商務(wù)建設(shè)、網(wǎng)絡(luò)推廣、移動互聯(lián)開發(fā)、研究、服務(wù)為一體的技術(shù)型公司。公司成立十余年以來,已經(jīng)為上千余家發(fā)電機維修各業(yè)的企業(yè)公司提供互聯(lián)網(wǎng)服務(wù)。現(xiàn)在,服務(wù)的上千余家客戶與我們一路同行,見證我們的成長;未來,我們一起分享成功的喜悅。
這兩個函數(shù)的區(qū)別是:pg_cancel_backend()函數(shù)實際上是給正在執(zhí)行的SQL任務(wù)配置一個取消標(biāo)志,正在執(zhí)行的任務(wù)是在合適的時候檢測到此標(biāo)志后主動退出;但如果這個任務(wù)沒有主動檢測到這個標(biāo)志,則該任務(wù)就無法正常退出,這時需要使用pg_terminate_backend()命令在終止SQL的執(zhí)行。
通常是先查詢pg_stat_activity,試圖找出長時間運行的SQL,然后進行終止,也可以批量終止回話:
SELECT 'SELECT pg_terminate_backend('||blocking_pid||');' from pg_blocking;