我希望能够在不同的线程中连接到不同的数据库,并在每个数据库中查询相同的模型。例如,没有线程,我可以做类似的事情:
# 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使用的连接池吗?