暂无图片
暂无图片
1
暂无图片
暂无图片
暂无图片

PG中如何判断 idle in transaction 为僵尸事务

AsherHu 2022-03-16
1102

1.idle in transaction

在日常运维过程中通过系统进程经常会看到一些idle in transaction 状态的连接,对于这种状态的连接我们怎么判断是不是僵尸事务呢?还是说此事务状态有还未提交的信息。

postgres=# select pid, state from pg_stat_activity ; 
pid |state

-------+---------------------
54168 | idle in transaction
51197 | idle
51983 | active
(11 rows)


复制

2.判断

在pg_stat_activity中查看idle in transaction 状态相关的二个状态backend_xid,backend_xmin 我们通过解读这个二个状态来确定是否是僵尸事务

backend_xid:用来表示会话是否申请了事务号

backend_xmin:事务会话的快照ID

如果backend_xid 和 backend_xmin 为空,可清理掉该进程, 如果不为空,说明事务还没结束,如未提交

3.示例

# 会话1
postgres=# begin; -- 执行begin 的时候没有事务好,只有在开始执行select 等语句时才有事务号
BEGIN
postgres=# select 1;
?column?
----------
1
(1 row)


postgres=# select pg_backend_pid() ;
pg_backend_pid
----------------
28493



#会话2
postgres=# \x
Expanded display is on.
postgres=# select * from pg_stat_activity where pid=28493 ;
-[ RECORD 1 ]----+------------------------------
datid | 13548
datname | postgres
pid | 28493
usesysid | 10
usename | postgres
application_name | psql
client_addr | 127.0.0.1
client_hostname |
client_port | 28736
backend_start | 2022-02-18 11:45:03.954147+08
xact_start | 2022-02-18 11:52:36.022063+08
query_start | 2022-02-18 11:52:49.399027+08
state_change | 2022-02-18 11:52:49.399425+08
wait_event_type | Client
wait_event | ClientRead
state | idle in transaction
backend_xid | -- 此时 backend_xid,和backend_xmin 值为空
backend_xmin |
query | select pg_backend_pid() ;
backend_type | client backend

# 注意:
从上面的截图我们可以看到会话的backend_xid和backend_xmin是空的,因为没有对数据库做任何操作所以没有申请事务号,由于是read committed的事务隔离级别,因此目前没有事务快照信息,backend_xmin为空。
如果后面数据有操作,那么backend_xid会有一个当前事务号或者查询当前事务号。

#会话1
postgres=# select txid_current(); --查看当前事务ID
txid_current
--------------
2170833
(1 row)

# 会话2
postgres=# select * from pg_stat_activity where pid=28493 ;
-[ RECORD 1 ]----+------------------------------
datid | 13548
datname | postgres
pid | 28493
usesysid | 10
usename | postgres
application_name | psql
client_addr | 127.0.0.1
client_hostname |
client_port | 28736
backend_start | 2022-02-18 11:45:03.954147+08
xact_start | 2022-02-18 11:52:36.022063+08
query_start | 2022-02-18 11:54:39.75218+08
state_change | 2022-02-18 11:54:39.752858+08
wait_event_type | Client
wait_event | ClientRead
state | idle in transaction
backend_xid | 2170833 -- backend_xid 值为当前事务ID
backend_xmin |
query | select txid_current();
backend_type | client backend


复制


文章转载自AsherHu,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论