1. Use Pgbouncer
Can take advantage of Pgbouncer'sserver_idle_timeout参数
Server_idle_timeout:
if inch Time -
Remove the previous comment to limit the automatic disconnection of the idle state beyond 60s. Of course, the connection mode set here is the session.
2. Combine the state and State_change fields in Pg_stat_activity
SELECTpg_terminate_backend (PID) frompg_stat_activityWHEREDatname= 'regress' andPid<>pg_backend_pid () andState= 'Idle' andState_change< Current_timestamp -INTERVAL'5'MINUTE;
Some may use the Query_start field in pg_stat_activity, but sometimes this field is empty, that is, the user just joins in but does not perform the action, at this time the field is empty, so try to use state_change more secure,
It is more convenient to use the pgbouncer.
Reference:
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?