ruby - 在 Ruby 中执行非阻塞 I/O 的首选方式是什么?

标签 ruby rubygems nonblocking

如果说我想检索一个网页进行解析,但在 I/O 发生时不阻塞 CPU。是否有与 Python 的 Eventlet 库等效的东西?

最佳答案

Ruby 的最佳 HTTP 客户端库是 Typhoeus ,它可用于以非阻塞方式并行执行多个 HTTP 请求。有阻塞和非阻塞接口(interface):

# blocking
response = Typhoeus::Request.get("http://stackoverflow.com/")
puts response.body

# non-blocking
request1 = Typhoeus::Request.new("http://stackoverflow.com/")
request1.on_complete do |response|
  puts response.body
end
request2 = Typhoeus::Request.new("http://stackoverflow.com/questions")
request2.on_complete do |response|
  puts response.body
end
hydra = Typhoeus::Hydra.new
hydra.queue(request1)
hydra.queue(request2)
hydra.run # this call is blocking, though

另一个选项是 em-http-request ,它在 EventMachine 之上运行。它有一个完全非阻塞的接口(interface):

EventMachine.run do
  request = EventMachine::HttpRequest.new('http://stackoverflow.com/').get
  request.callback do
    puts request.response
    EventMachine.stop
  end
end

还有一个接口(interface)可以并行发出许多请求,类似于 Typhoeus Hydra。

em-http-request 的缺点是它绑定(bind)到 EventMachine。 EventMachine 本身就是一个很棒的框架,但它是一个孤注一掷的交易。您需要以事件/连续传递风格的方式编写整个应用程序,众所周知,这会导致脑损伤。 Typhoeus 更适合尚未发生事件的应用程序。

关于ruby - 在 Ruby 中执行非阻塞 I/O 的首选方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4468471/

相关文章:

ruby - 如何转换 slim 到 html?

linux - 非阻塞 Linux 服务器套接字

ruby - 重新打开 Ruby 类的奇怪问题

ruby - 如何在 Rails 3 中实现安全性?

ruby - 无法在 OS X Mavericks Xcode 5.1 上安装 CocoaPods

ruby-on-rails - 用于生成与 Rails 3 beta 兼容的动态/ajax crud 接口(interface)的 Rails 插件?

dialog - Applescript 中的非阻塞对话框

scala - 为什么阻止 future 被认为是一种不好的做法?

ruby - rspec --drb 不适用于 Spork 的 RSpec

ruby-on-rails - 火腿 + mustache