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

如何自动关闭PostgreSQL中的空闲连接?

有些客户端连接到我们的postgresql数据库,但保持打开连接。
在一定量的不活动状态之后,是否可以告诉Postgresql关闭这些连接?

TL; DR

IF you’re using a Postgresql version >= 9.2
THEN use 07000

IF you don’t want to write any code
THEN use 07001

对于有兴趣的人来说,这里是我从 Craig Ringer评论中提出的解决方案:

You Could use a cron job to look at when the connection was last active (see pg_stat_activity) and use pg_terminate_backend to kill old ones. Easily expressed in a simple query. I’m not sure if pg_terminate_backend was available in the pretty-ancient 8.3,though.

所选解决方案如下:

>首先,我们升级到Postgresql 9.2。
>然后,我们安排线程每秒运行一次。
>当线程运行时,它会查找任何旧的非活动连接。

  • A connection is considered inactive if its state is either idle,idle in transaction,idle in transaction (aborted) or disabled.
  • A connection is considered old if its last state has changed for more than 5 minutes.

>还有一些额外的线程和上面的一样。但是,这些线程与不同的用户连接到数据库
>我们至少为连接到我们的数据库的任何应用程序打开一个连接。 (rank()函数)

这是线程运行的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

原文地址:https://www.jb51.cc/postgresql/193150.html

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

相关推荐