Postgresql关闭idle连接

发布于:2023-09-14 ⋅ 阅读:(96) ⋅ 点赞:(0)

1.  postgresql < 9.6

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;

2. postgresql >=9.6   

3.postgresql >=14

idle_session_timeout =  60

4.pgbouncer:

client_idle_timeout=300

server_lifetime = 120

5. 删除错误配置:

#!/bin/bash
for dir in $(ls ./)
 do
     [ -d $dir ] && echo $dir
     sed -i '$d' ${dir}/postgresql.conf
 done