LoginSignup
3
3

More than 5 years have passed since last update.

水平分割されたDBにクエリを発行してデータを取得する

Last updated at Posted at 2015-09-29

必要に迫られて書いたのでメモを残しておく。
DBはMysql、要ssh接続。
net-ssh-gatewayparallelmaysql2を使用。
スレッドを使用して並列に処理する。プロセスでも特に問題なく動作するはず。(動作確認していない)

query.rb
require 'net/ssh/gateway'
require 'mysql2'
require 'parallel'

gw = Net::SSH::Gateway.new(
  'host',
  'user'
)

db_address = ->(i){ "database_server#{i}" }
db_name = ->(i){ "db_#{i}" }

query = <<EOQ
select *
from hoge
EOQ

result = Parallel.map(0.upto(db_count - 1), in_threads: 4) do |i|
  res = []
  gw.open(db_address.call(i), 3306) do |port|
    client = Mysql2::Client.new(
      host: '127.0.0.1',
      username: 'username',
      password: 'password',
      database: db_name.call(i),
      port: port
    )
    client.query(sql).each{|row| res << row}
    res
  end
end

result = result.flatten

ハッシュの配列が戻ってくるので、あとは煮るなり焼くなり。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3