怎么理解PostgreSQL中session hang情况

52次阅读
没有评论

共计 1805 个字符,预计需要花费 5 分钟才能阅读完成。

这篇文章主要介绍“怎么理解 PostgreSQL 中 session hang 情况”,在日常操作中,相信很多人在怎么理解 PostgreSQL 中 session hang 情况问题上存在疑惑,丸趣 TV 小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”怎么理解 PostgreSQL 中 session hang 情况”的疑惑有所帮助!接下来,请跟着丸趣 TV 小编一起来学习吧!

在执行 SQL 的时候可能会碰到 session hang 的情况,这时候我们其实不知道是因为 SQL 本身执行很慢还是因为 lock 导致 hang,因此一般情况下需要通过查询 pg_stat_activity、pg_locks 等系统表来确认。除之之外,PG 还提供了通过 statement timeout 的超时机制来处理这种情况。

session 1
创建数据表,启动事务,执行查询

testdb=# create table t_timeout(id int);
CREATE TABLE
testdb=# 
testdb=# begin;
BEGIN
testdb=# 
testdb=# select count(*) from t_timeout;
 count 
-------
 0
(1 row)
testdb=# select * from pg_locks where pid = pg_backend_pid();
 locktype | database | relation | page | tuple | virtualxid | transactionid | classid | ob
jid | objsubid | virtualtransaction | pid | mode | granted | fastpath 
------------+----------+----------+------+-------+------------+---------------+---------+---
----+----------+--------------------+------+-----------------+---------+----------
 relation | 16384 | 11645 | | | | | | 
 | | 3/94 | 1719 | AccessShareLock | t | t
 virtualxid | | | | | 3/94 | | | 
 | | 3/94 | 1719 | ExclusiveLock | t | t
 relation | 16384 | 286770 | | | | | | 
 | | 3/94 | 1719 | AccessShareLock | t | f
(3 rows)
testdb=#

session 2
执行 alter table 命令,hang 住

testdb=# -- session 2
testdb=# alter table t_timeout add column c1 int;
--  挂起 

设置 50ms 超时,SQL 返回超时错误

testdb=# begin;
BEGIN
testdb=# SET statement_timeout = 50;
testdb=# alter table t_timeout add column c1 int;
ERROR: canceling statement due to statement timeout
testdb=#

不过这样的设置,需要 DBA 对 SQL 的执行时长有初步的估算,比如增加列操作,正常应在 10ms 内返回,那设置超时 50ms 是没有问题,但对于 vacuum full 这样的操作来说,设置为 50ms 就很不合适了。

testdb=# SET statement_timeout = 50;
testdb=# vacuum full;
ERROR: canceling statement due to statement timeout
testdb=#

也就是说,设置超时会存在误伤,需谨慎使用。

到此,关于“怎么理解 PostgreSQL 中 session hang 情况”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注丸趣 TV 网站,丸趣 TV 小编会继续努力为大家带来更多实用的文章!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-07-26发表,共计1805字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)