使用事件机生成二维码

Generate qr-code with event machine

我正在开发 API,基于 EventMachine 回显服务器。它监听特定端口和 returns html-页面上的请求,上面有二维码,它是根据请求查询的参数生成的。问题是,将字符串打包成二维码的评估方法需要 8 到 11 秒,这是不可接受的。我不知道为什么会这样,除了它可能与事件机器有关。

P.S。在 irb 中,相同的代码 RQRCode::QRCode.new(my_string, :size => 10,:level => :l) 不到 1 秒。

我尝试了两种不同的 gem:rqrcode 和 barby+rqrcode。两者显示相同的结果。

代码示例:

require 'eventmachine'
require 'rqrcode'

class Handler < EventMachine::Connection

  def receive_data(data)
    puts Time.now
    qrcode = RQRCode::QRCode.new('some_string', :size => 10,:level => :l)
    puts Time.now
    return qrcode
  end
end

EventMachine::run {
  EventMachine::start_server("0.0.0.0", 8081, Handler)
  puts "Listening..."
}

输出:

2015-05-12 18:03:38 +0300
2015-05-12 18:03:48 +0300

看来你需要打电话给close_connection。这是 EventMachine 的 echo server example

 require 'eventmachine'

 module EchoServer
   def post_init
     puts "-- someone connected to the echo server!"
   end

   def receive_data data
     send_data ">>>you sent: #{data}"
     close_connection if data =~ /quit/i # <---- This is what you're missing -----
   end

   def unbind
     puts "-- someone disconnected from the echo server!"
   end
end

# Note that this will block current thread.
EventMachine.run {
  EventMachine.start_server "127.0.0.1", 8081, EchoServer
}

如果您的时间戳始终(几乎)恰好相隔 10 秒,我敢打赌请求结束是因为超时而不是响应。使用 QR 数据响应后,调用 close_connection 让浏览器知道您已正确完成。

Edit 看起来您也没有调用 send_data(并引用 Tume 而不是 Time)。看起来您需要使用 send_data,而不是 return。您的代码片段实际上 运行 在您的服务器上吗?

更新 运行 在调试模式下显着降低了 QR 生成速度。

问题是我 运行 服务器处于 RubyMine 的调试模式。从控制台启动服务器解决了问题,生成二维码大约需要 1 秒。