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