querrel
1.0.0
Querrel 可以轻松地使用 ActiveRecord 并行(线程)查询多个数据库,就像查询一个数据库一样。
将此行添加到应用程序的 Gemfile 中:
gem 'querrel'
然后执行:
$ bundle
或者自己安装:
$ gem install querrel
您可以通过 Querrel 的顶级命名空间直接使用它,或者通过创建一个实例来使用:
all_brands = Querrel . query ( Brand . all , on : [ 'db1' , 'db2' , 'db3' ] )
# is the same as
all_brands = Querrel . new ( [ 'db1' , 'db2' , 'db3' ] ) . query ( Brand . all )
上述任一方法都会为您提供所有给定数据库中所有品牌对象的数组。这些记录将被标记为只读。
query
将生成一个带有传入的ActiveRecord::Relation
块,这允许您在合并结果之前对结果执行其他操作,例如您可以使用 pluck:
all_brand_names = q . query ( Brand . all ) do | s |
s . pluck ( :name )
end
还有一个run
方法,它不是运行预定的范围和合并,而是采用一个块,允许您对指定的数据库连接执行任何您想要的操作,例如:
require 'thread'
all_brands = [ ]
b_s = Mutex . new
all_products = [ ]
p_s = Mutex . new
Querrel . run ( on : dbs ) do | db |
b_s . synchronize { all_brands += Brand . all . to_a }
p_s . synchronize { all_products += Product . all . to_a }
end
您可以通过三种方式指示 Querrel 使用哪些数据库:
传入一组环境,例如Querrel.new([:customer1, :customer2])
传入数据库名称数组,例如Querrel.new(['dbs/customer1.sqlite3', 'dbs/customer2.sqlite3'], db_names: true)
传入命名连接配置的哈希值,例如:
Querrel . new ( {
one : {
adapter : "sqlite3" ,
database : "test/dbs/test_db_1.sqlite3"
} ,
two : {
adapter : "sqlite3" ,
database : "test/dbs/test_db_2.sqlite3"
}
} )
默认情况下,Querrel 将使用最多 20 个线程,但您可以使用:threads
选项进行调整:
q = Querrel . new ( dbs , threads : 50 )
git checkout -b my-new-feature
)git commit -am 'Add some feature'
)git push origin my-new-feature
)