我正在尝试使用EM :: Synchrony通过使它们异步来加速我的查询。下面是github page中的示例,我正在进行2次异步查询:
EventMachine.synchrony do
db = EventMachine::Synchrony::ConnectionPool.new(size: 2) do
Mysql2::EM::Client.new(
:host => config[:server],
:username => config[:user],
:password => config[:pwd],
:database => config[:db_name]
)
end
multi = EventMachine::Synchrony::Multi.new
multi.add :a, db.aquery("
select count(distinct userid) from my_table
where date = '2013-09-28'
")
multi.add :b, db.aquery("
select count(distinct userid) from my_table
where date = '2013-09-27'
")
res = multi.perform
puts res
# p "Look ma, no callbacks, and parallel MySQL requests!"
# p res.responses[:callback][0]
EventMachine.stop
end
> #<EventMachine::Synchrony::Multi:0x00000001eb8da8>
我的问题是如何设置回调以实际获取查询返回的值?我想要做的是一旦查询完成,将它们聚合在一起并写入另一个表或csv或其他任何内容。感谢。
答案 0 :(得分:0)
也许你不需要Synchrony?无论如何,它们都是异步的。 https://github.com/brianmario/mysql2#eventmachine
但如果你确实需要那么答案可能是
res.responses[:callback][:a]
res.responses[:callback][:b]
https://github.com/igrigorik/em-synchrony/blob/master/lib/em-synchrony/em-multi.rb#L17
答案 1 :(得分:0)
我发现以下代码会向我提供查询结果:
res.responses[:callback].each do
|obj|
obj[1].callback do
|rows|
rows.each do
|row|
puts row.inspect
end
end
end
$ruby async_mysql.rb
{"count(distinct ui)"=>159}
{"count(distinct ui)"=>168}