简体   繁体   中英

How to kill the idle connection in Postgresql.?

我正在使用 java servlet 和 pgadmin 9.1。问题是 servlet 中的连接没有正确关闭,因此如果达到最大连接会导致黑屏。我不希望每个用户都在 pgadmin 中扩展最大连接...我在 servlet 的起点和终点使用了以下查询,但它显示的错误如..connection因管理员命令而终止..

ResultSet rs_1q=st_Query3.executeQuery("SELECT pg_terminate_backend(pg_stat_activity.procpid)FROM pg_stat_activity WHERE pg_stat_activity.current_query = '<IDLE>' AND procpid <> pg_backend_pid();");

Generally, as @Rahul points out, its not advisable to kill connections. But if it's your last resort, this is how to terminate idle connections:

SELECT pg_terminate_backend(pid) FROM pg_stat_activity
WHERE datname = 'databasename'
AND pid <> pg_backend_pid()
AND state in ('idle');

I dont think that killing a connection is an ideal solution as there may be certain connection which might be genuinely waiting for the transaction to get completed. Instead I would suggest you to set a timeout for your transacion.

However if you are desperate to kill the idle connections then you can try like this:

Use shell script and do "ps auxwww|grep 'idle in transaction'" which will return list of all "idle in transaction." processes. Then you can use "awk" and find of each line of output to get the the process id, and finally you can use a "kill <pid>" to each process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM