我想以并发方式执行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
最佳答案
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
关于mysql - eventmachine和mysql2/em不回调,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22473432/