Rails 3 DB连接池-连接不关闭。

时间:2022-08-04 17:00:00

Stack is Rails 3 / Postgres + mongrel. I recently had to increase the connection pool because hits on one of the mongrels were always timing out. I reasoned that with 3 mongrels + a delayed_job running on each, I'd need 6 connections in the pool (it was set to 5). I increased this to 10 in database.yml and it resolved the timeout issues, now though when I monitor connections in PG I am seeing this sort of thing;

堆栈是Rails 3 / Postgres + mongrel。最近我不得不增加连接池,因为在一个mongrels上的点击总是超时。我推断有3个杂种+一个delayed_job,我需要在池中有6个连接(它被设置为5),我在数据库中将它增加到10个。yml和它解决了超时问题,现在当我监视PG中的连接时,我看到了这样的事情;

SELECT datname,usename,procpid,client_addr,waiting,query_start,current_query FROM pg_stat_activity;


db1   | www-data |    8658 |             | f       | 2014-03-19 10:03:54.084825+00 | <IDLE>
db1   | www-data |    9071 |             | f       | 2014-03-19 09:58:42.306558+00 | <IDLE>
db1   | www-data |    8721 |             | f       | 2014-03-19 10:03:53.980691+00 | <IDLE>
db1   | www-data |    8722 |             | f       | 2014-03-19 10:03:53.874443+00 | <IDLE>
db1   | www-data |    8733 |             | f       | 2014-03-19 10:04:20.380137+00 | <IDLE>
db1   | www-data |    9080 |             | f       | 2014-03-19 10:00:54.157541+00 | <IDLE>
db1   | www-data |   10843 |             | f       | 2014-03-19 10:04:18.506355+00 | <IDLE>
#and so on and so on for more than 20 instances...

It baloons up to more than 20 connections and seemingly isn't closing them (I'm assuming that the presence of still means they're open, just not doing anything). It does seem to go up and down, so some connections are being closed.

它可以连接超过20个连接,而且似乎并没有关闭它们(我假设still的存在意味着它们是打开的,只是不做任何事情)。它看起来确实有涨有跌,所以一些连接被关闭了。

I thought rails/activerecord was supposed to close its connections automatically but this doesn't seem to be the case.

我认为rails/activerecord应该自动关闭它的连接,但事实并非如此。

Have I read this correctly? Do I have a leak somewhere? What could be causing it?

我读对了吗?我哪里漏了吗?是什么引起的呢?

1 个解决方案

#1


2  

When using ActiveRecord transactions outside of actions initiated by a controller e.g. in a delayed job, you must use the following syntax to ensure connections are returned to the pool

当在控制器发起的操作之外使用ActiveRecord事务时,例如在延迟的作业中,必须使用以下语法来确保连接返回到池中

ActiveRecord::Base.connection_pool.with_connection do
  #your code here
end

#1


2  

When using ActiveRecord transactions outside of actions initiated by a controller e.g. in a delayed job, you must use the following syntax to ensure connections are returned to the pool

当在控制器发起的操作之外使用ActiveRecord事务时,例如在延迟的作业中,必须使用以下语法来确保连接返回到池中

ActiveRecord::Base.connection_pool.with_connection do
  #your code here
end