mysql - eventmachine 和 mysql2/em 不回调

标签 mysql ruby eventmachine

我想并发执行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/

相关文章:

Ruby EventMachine 测试

MYSQL - 如何将数据插入另一个服务器数据库表

mysql - eclipselink-2.5.2 Spring 4.1.1 没有事务当前处于事件状态错误

ruby - 如何在 Ruby 类中使​​用 if 语句?

ruby - 通过网络套接字扩展多 channel 发布/订阅

ruby - QtRuby 与 DRb 或 EventMachine

php - 高效评论系统分页查询

php - 使用未定义的常量项目 - 假定为 'project'(这将在未来的 PHP 版本中引发错误)

ruby - 即使失败也继续进行多主机测试

ruby-on-rails - 如何为 UTF-8 字符串编写带有大引号的 gsub?