我想多線程我的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?