如何自动关闭PostgreSQL中的空闲连接?
有些客户端连接到我们的postgresql数据库,但保持打开连接。
在一定量的不活动状态之后,是否可以告诉Postgresql关闭这些连接? TL; DR
对于有兴趣的人来说,这里是我从
Craig Ringer的评论中提出的解决方案:
所选解决方案如下: >首先,我们升级到Postgresql 9.2。
>还有一些额外的线程和上面的一样。但是,这些线程与不同的用户连接到数据库。 这是线程运行的SQL查询: WITH inactive_connections AS ( SELECT pid,rank() over (partition by client_addr order by backend_start ASC) as rank FROM pg_stat_activity WHERE -- Exclude the thread owned connection (ie no auto-kill) pid <> pg_backend_pid( ) AND -- Exclude known applications connections application_name !~ '(?:psql)|(?:pgAdmin.+)' AND -- Include connections to the same database the thread is connected to datname = current_database() AND -- Include connections using the same thread username connection usename = current_user AND -- Include inactive connections only state in ('idle','idle in transaction','idle in transaction (aborted)','disabled') AND -- Include old connections (found with the state_change field) current_timestamp - state_change > interval '5 minutes' ) SELECT pg_terminate_backend(pid) FROM inactive_connections WHERE rank > 1 -- Leave one connection for each application connected to the database (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |