我想将sql查询作为并发执行。所以我在linux上的ruby 2.1.1上使用了eventmachine和mysql2 / em。
但是 eventmachine不会调用回调。
当我的脚本运行时,这已经过时了
"loop start"
"sql: select id from table where id = 1"
"loop end"
"loop start"
"sql: select id from table where id = 2"
"loop end"
"loop start"
"next loop"
"loop start"
"next loop"
.....
我想要这个输出。
"loop start"
"sql: select id from table where id = 1"
"loop end"
"loop start"
"sql: select id from table where id = 2"
"loop end"
"loop start"
"next loop"
"callback"
"results"
"loop start"
"sql: select id from table where id = 3"
.....
有什么问题?
#!/usr/bin/env ruby
=begin
Gemfile
source 'https://rubygems.org'
gem 'eventmachine'
gem 'mysql2'
gem 'pry'
gem 'pry-debugger'
=end
require 'pp'
require 'bundler'
Bundler.require
require 'mysql2/em'
MYSQLINFO = {
host: 'localhost',
username: 'root',
password: '',
port: 3306,
}
SQLS = [
'select id from table where id = 1',
'select id from table where id = 2',
'select id from table where id = 3',
'select id from table where id = 4',
]
CONCURRENCY = 2
clients = []
CONCURRENCY.times do
clients << Mysql2::EM::Client.new(MYSQLINFO)
end
EM.run do
while true
pp 'loop start'
client = clients.shift
if client.nil?
# FIXME: I guess this point is wrong. Context must go to reactor thread?
# but I don't know how to do.
pp 'next loop'
next
end
sql = SQLS.shift
if sql.nil?
break
end
defer = client.query(sql)
pp "sql: #{sql}"
defer.callback do |results|
clients << client
pp 'callback'
pp results
end
pp 'loop end'
end
EM.stop
end
答案 0 :(得分:0)
正如我在办公室提到的,也许你不必在这里忙碌。 我认为每个客户端都应该在回调中调用下一个查询。
答案 1 :(得分:0)
Y = lambda do |f|
lambda {|g| g[g]}[lambda do |g|
f[lambda {|*args| g[g][*args]}]
end]
end
EM.run do
sql = 'select oppai from boins'
clients.each do |client|
Y[lambda {|f| lambda {|client, sql|
client.query(sql).callback do |result|
pp result.to_a.inspect
f[client, sql]
end
}}][client, sql]
end
end