Ruby on rails 每个线程有不同的数据库连接,同一型号?

Ruby on rails 每个线程有不同的数据库连接,同一型号?,ruby-on-rails,multithreading,activerecord,Ruby On Rails,Multithreading,Activerecord,我希望能够在单独的线程中连接到不同的数据库,并在每个数据库中查询相同的模型。例如,如果没有线程,我可以执行以下操作: # given 'db1' and 'db2' are rails environments with connection configurations ['db1', 'db2'].each do |db| Post.establish_connection(db) Post.where(title: "Foo") end Post.establish_conne

我希望能够在单独的线程中连接到不同的数据库,并在每个数据库中查询相同的模型。例如,如果没有线程,我可以执行以下操作:

# given 'db1' and 'db2' are rails environments with connection configurations
['db1', 'db2'].each do |db|
  Post.establish_connection(db)

  Post.where(title: "Foo") 
end
Post.establish_connection(Rails.env)
这将在两个数据库上循环,并在每个数据库中查找帖子。我需要能够使用线程并行执行此操作,如:

['db1', 'db2'].each do |db|
  threads = Thread.new do
    Post.establish_connection(db)

    Post.where(title: "Foo")
  end 
end
threads.join
Post.establish_connection(Rails.env)
但是很明显,使用全局Post类在每个线程中建立一个新的连接池不是线程安全的

我想做的是在每个线程中建立一个新的连接池。我走了这么远:

['db1', 'db2'].each do |db|
  threads = Thread.new do
    conf = ActiveRecord::ConnectionAdapters::ConnectionSpecification.new(Rails.configuration.database_configuration[db], "mysql2_connection")
    pool = ActiveRecord::ConnectionAdapters::ConnectionPool.new(conf)
    pool.with_connection do |con|
      # problem is, I have this con object but using the Post class still uses the thread's default connection.
      Post.where(title: "Foo")
    end
  end 
end
threads.join

必须有一种方法可以让我逐个线程地更改ActiveRecord使用的连接池?

您找到解决方案了吗?我现在有点处境相同。我无法让它与AR一起工作,我必须直接使用连接,我在这里解释: