如何释放未被客户端应用程序正确关闭的Postgresql连接?
我有一个数据挖掘应用程序,可以旋转多个进程,所有连接到本地Postgresql 9.1数据库以检索数据.它可以运行几个小时,但随后出现错误:
FATAL: remaining connection slots are reserved for non-replication superuser connections
研究这表明,这很可能是由于应用程序没有正确关闭它的连接.但是,即使应用程序被杀死,这些连接也永远不会被释放.是不是存在某种超时,Postgresql会自动关闭连接?
我也尝试将Postgres的max_connections从100增加到200,但重新启动给了我错误:
2014-02-23 10:51:15 EST FATAL: could not create shared memory segment: Invalid argument 2014-02-23 10:51:15 EST DETAIL: Failed system call was shmget(key=5432001,size=36954112,03600). 2014-02-23 10:51:15 EST HINT: This error usually means that Postgresql's request for a shared memory segment exceeded your kernel's SHMMAX parameter. You can either reduce the request size or reconfigure the kernel with larger SHMMAX. To reduce the request size (currently 36954112 bytes),reduce Postgresql's shared memory usage,perhaps by reducing shared_buffers or max_connections. If the request size is already small,it's possible that it is less than your kernel's SHMMIN parameter,in which case raising the request size or reconfiguring SHMMIN is called for. The Postgresql documentation contains more information about shared memory configuration.
我的系统是Ubuntu 12.04并且有8GB内存,所有其他PG设置都是默认设置,所以我不确定为什么它认为系统没有足够的内存.
然后我尝试使用pgbouncer来池和重用连接.这似乎工作得更好一点,但即使这最终耗尽了连接,给我错误:
ERROR: no more connections allowed
如何进一步诊断和解决此问题?
您可以通过更改最大共享内存设置来增加最大连接数,但是如果问题是您的连接没有被关闭,那么您应该真正解决这个问题.如果软件不受您的控制而且由于没有关闭连接而导致错误,您可以使用一些cron作业,例如:
原文链接:https://www.f2er.com/postgresql/192564.htmlselect pg_terminate_backend(procpid) from pg_stat_activity where usename = 'yourusername' and current_query = '<IDLE>' and query_start < current_timestamp - interval '5 minutes' ;
这就是我用来杀死类似漏洞软件泄漏连接的方法.
或者,您可以通过连接池运行您的错误软件,该连接池具有类似于杀死空闲连接(例如pgpool)的功能.
注意:较新版本的Postgres列名略有不同:
select pg_terminate_backend(pid) from pg_stat_activity where usename = 'YOURDATABASEUSERNAME*' and state = 'idle' and query_start < current_timestamp - interval '5 minutes' ;