某些客戶端連接到我們的postgresql數據庫,但保持連接打開。 是否可以告訴Postgresql在一定數量的不活動之後關閉這些連接?如何自動關閉PostgreSQL中的空閒連接?
TL; DR
如果您使用PostgreSQL的版本> =
9.2
然後用the solution I came up with如果你不想寫任何代碼
然後使用arqnid's solution
某些客戶端連接到我們的postgresql數據庫,但保持連接打開。 是否可以告訴Postgresql在一定數量的不活動之後關閉這些連接?如何自動關閉PostgreSQL中的空閒連接?
TL; DR
如果您使用PostgreSQL的版本> =
9.2
然後用the solution I came up with如果你不想寫任何代碼
然後使用arqnid's solution
對於那些有興趣誰,這裏是我想出了一個解決方案,從Craig Ringer的評論的啓發:
(...)使用cron作業來看看當連接最後有效(見和pg_stat_activity),並使用pg_terminate_backend殺死舊的(...)
選擇的解決方案可以歸結如下:。
- 的連接被認爲是不活動的如果其狀態要麼
idle
,idle in transaction
,idle in transaction (aborted)
或disabled
。- 連接被認爲是舊如果其最後狀態已經改變超過5分鐘。
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
你可以使用cron作業來看看,當連接上一個活動(見'pg_stat_activity')和使用' pg_terminate_backend'來殺死舊的。以簡單的查詢輕鬆表達。不過,我不確定'pg_terminate_backend'在古老的8.3中是否可用。 –