微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

查找和杀掉postgresql堵塞的会话

查找和杀掉postgresql堵塞的会话
1.创建视图,可以随时使用:
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;
查询创建的视图查询堵塞:
select  * from  pg_blocking;
2.杀掉查出的阻塞会话:
kill有两种方式,第一种是:
SELECT pg_cancel_backend(PID);  ###取消一个正在执行的sql
第二种是:
SELECT pg_terminate_backend(PID);  ###终止一个后台服务进程,同时释放此后台服务进程的资源。

这两个函数的区别是:pg_cancel_backend()函数实际上是给正在执行的sql任务配置一个取消标志,正在执行的任务是在合适的时候检测到此标志后主动退出;但如果这个任务没有主动检测到这个标志,则该任务就无法正常退出,这时需要使用pg_terminate_backend()命令在终止sql的执行。
通常是先查询pg_stat_activity,试图找出长时间运行的sql,然后进行终止,也可以批量终止回话:
SELECT  'SELECT pg_terminate_backend('||blocking_pid||');' from pg_blocking;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐