我想多线程我的rails应用程序,但遇到了connection_pool的一些问题。我启动一个线程并执行一个数据库查询,但它似乎永远不会关闭在该线程中创建的数据库连接。这是我的代码:Rails 4 multithreading和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.times {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应该采取一个块,并用它,然后关闭连接执行它,但根据我的输出没有关系“T。我真的不明白。
有没有人有任何解决方案或想法,为什么这可能会发生?是否正确使用“connection_pool.connections.size”来检查有多少个连接?
有没有其他的方式来实现多线程的数据库查询在rails?