標籤:style blog http io color os ar 使用 for
1、use pgbouncer
可以利用pgbouncer的server_idle_timeout參數
server_idle_timeout:
;; Close server connection if its not been used in this time.;; Allows to clean unnecessary connections from pool after peak.;server_idle_timeout = 60
去掉前面的注釋,限定idle狀態超過60s的自動中斷連線。當然這裡設定的串連模式是session。
2、結合pg_stat_activity中的state和state_change欄位
SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = ‘regress‘ AND pid <> pg_backend_pid() AND state = ‘idle‘ AND state_change < current_timestamp - INTERVAL ‘5‘ MINUTE;
有的可能使用pg_stat_activity中的query_start欄位,但有時這個欄位是空的,即使用者只是串連進來但沒有執行操作,此時該欄位顯示空,所以盡量使用state_change較穩妥,
使用pgbouncer就更方便了。
參考:
http://stackoverflow.com/questions/13236160/is-there-a-timeout-for-idle-postgresql-connections
http://www.postgresql.org/docs/9.3/static/monitoring-stats.html#PG-STAT-ACTIVITY-VIEW
Is it possible to configure PostgreSQL to automatically close idle connections?