我正在尝试多线程我的rails应用程序,但是遇到了connection_pool的一些问题。我启动了一个线程并执行数据库查询,但在线程中创建的数据库连接似乎从未关闭过。这是我的代码:
class A
def self.foo
Thread.new do
nc1 = ActiveRecord::Base.connection_pool.connections.size
nw = ""
nc2 = ""
ActiveRecord::Base.connection_pool.with_connection do |conns|
nw = Person.count
nc2 = ActiveRecord::Base.connection_pool.connections.size
end
nc3 = ActiveRecord::Base.connection_pool.connections.size
puts "First there were #{nc1} connections, after things there were #{nc2} and now finally there are #{nc3} connections, there are #{nw} people in the db"
end
end
end当我执行10.x {A.foo}时,它会给出以下输出。
First there were 1 connections, after things there were 3 and now finally there are 5 connections, there are 5325 people in the db
First there were 1 connections, after things there were 4 and now finally there are 5 connections, there are 5325 people in the db
First there were 1 connections, after things there were 2 and now finally there are 5 connections, there are 5325 people in the db
First there were 1 connections, after things there were 5 and now finally there are 5 connections, there are 5325 people in the db
First there were 1 connections, after things there were 5 and now finally there are 5 connections, there are 5325 people in the db
First there were 1 connections, after things there were 5 and now finally there are 5 connections, there are 5325 people in the db
First there were 1 connections, after things there were 5 and now finally there are 5 connections, there are 5325 people in the db
First there were 1 connections, after things there were 5 and now finally there are 5 connections, there are 5325 people in the db
First there were 1 connections, after things there were 5 and now finally there are 5 connections, there are 5325 people in the db
First there were 1 connections, after things there were 5 and now finally there are 5 connections, there are 5325 people in the db最后我跑起来:
ActiveRecord::Base.connection_pool.connections.size
5现在根据documentation的说法,with_connection应该通过一个连接来执行它,然后它会关闭,但是根据我的输出,它没有,我真的不明白。
有没有人有任何解决方案或想法,为什么会发生这种情况?使用"connection_pool.connections.size“是检查有多少连接的正确方式吗?
是否有其他方法可以在rails中实现多线程数据库查询?
发布于 2015-06-10 18:10:33
好吧,我只是不理解connection_pool是如何工作的。连接池保存自创建池以来已打开的连接,无论它们是否正在使用。因此,我的问题的答案是,您无法(以目前的实现方式)通过connection_pool来查看哪些连接正在被活跃地使用。相反,我对连接池本身进行了修补,以包含此功能。
如果有人感兴趣,这是我在config/initializers/connection_pool_patch.rb中的补丁:
module ActiveRecord
module ConnectionAdapters
class ConnectionPool
def num_available
@available.size
end
end
end
end
module ActiveRecord
module ConnectionAdapters
class ConnectionPool
class Queue
def size
@queue.size
end
end
end
end
end它暴露了私有列表@available的大小,该私有列表保存了连接池中可用(即当前未使用但已打开)的连接。用法= ActiveRecord::Base.connection_pool.num_available
https://stackoverflow.com/questions/30376078
复制相似问题