每个线程不同的数据库连接,相同的型号

Mik*_*ell 6 activerecord multithreading ruby-on-rails

我希望能够在不同的线程中连接到不同的数据库,并在每个数据库中查询相同的模型.例如,没有线程,我可以做类似的事情:

# 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)
Run Code Online (Sandbox Code Playgroud)

这将遍历两个数据库并查找每个数据库中的帖子.我需要能够使用线程并行执行此操作,例如:

['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)
Run Code Online (Sandbox Code Playgroud)

但很明显,使用全局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
Run Code Online (Sandbox Code Playgroud)

我必须有一种方法可以在逐个线程的基础上更改ActiveRecord使用的连接池吗?