[英]Rails 4 multithreading and connection_pool problems
我正在嘗試對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次{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
現在,根據文檔, with_connection應該包含一個塊並使用連接將其執行,然后關閉該連接,但是根據我的輸出,它沒有。 我真的不明白。
是否有人有任何解決方案或想法可能會發生這種情況? 使用“ connection_pool.connections.size”是檢查多少個連接的正確方法嗎?
還有其他方法可以在Rails中實現多線程數據庫查詢嗎?
好的,所以我只是不了解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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.