你如何释放PostgreSQL连接不能被客户端应用程序正确closures?
我有一个数据挖掘应用程序,它可以启动多个进程,所有连接到本地PostgreSQL 9.1数据库来检索数据。 它运行好几个小时,但随后死亡的错误:
FATAL: remaining connection slots are reserved for non-replication superuser connections
研究表明,这很可能是由于应用程序没有正确closures它的连接而造成的。 但是,即使应用程序被杀死,这些连接也不会被释放。 PostgreSQL会自动closures连接吗?
我也尝试增加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
我如何进一步诊断和解决这个问题?
您可以通过更改最大共享内存设置来增加最大连接数,但是如果问题是连接没有closures,那么您应该真正解决这个问题。 如果软件超出了你的控制范围,并且由于没有closures连接而出现错误,你可以使用一些cron作业:
select pg_terminate_backend(procpid) from pg_stat_activity where usename = 'yourusername' and current_query = '<IDLE>' and query_start < current_timestamp - interval '5 minutes' ;
这就是我所做的杀死类似漏洞软件的漏洞。
另外,你也许可以通过一个连接池来运行你的bug软件,这个连接池有类似的function来杀死空闲连接,比如pgpool。
对于较新版本的PostgreSQL:
select pg_terminate_backend(pid) from pg_stat_activity where usename = 'YOURDATABASEUSERNAME*' and state = 'idle' and query_start < current_timestamp - interval '5 minutes' ;
以上将帮助您终止您的空闲连接。 我有同样的问题,但事实certificate,我的Flask和SQLAlchemy的方式连接到数据库的问题。
* usename不是拼写错误
关于pipe理内核资源的PG文档 。 这应该可以帮助你增加内核的内存限制。