2

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

回答

0

好吧,我只是不明白connection_pool的工作原理。連接池保存自池創建以來已打開的連接,無論它們是否正在使用。所以我的問題的答案是,你不能(以今天實現的方式)connection_pool來查看哪些連接正在被主動使用。相反,我修補連接池本身以包含此功能。

如果有人有興趣,這是我的補丁放置在配置/初始化/ 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