在 Ruby 中执行非阻塞 I/O 的首选方式是什么? [英] What is the preferred way of performing non blocking I/O in Ruby?
问题描述
如果说我想检索一个网页进行解析,但在 I/O 发生时不阻塞 CPU.有没有相当于 Python 的 Eventlet 库的东西?
If say I want to retrieve a web page for parsing, but not block the CPU while the I/O is taking place. Is there something equivalent to Python's Eventlet library?
推荐答案
Ruby 最好的 HTTP 客户端库是 Typhoeus,它可用于以非阻塞方式并行执行多个 HTTP 请求.有阻塞和非阻塞接口:
The best HTTP client library for Ruby is Typhoeus, it can be used to perform multiple HTTP requests in parallel in a non-blocking fashion. There is a blocking and non-blocking 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 之上.它有一个完全非阻塞的接口:
Another option is em-http-request, which runs on top of EventMachine. It has a completely non-blocking interface:
EventMachine.run do
request = EventMachine::HttpRequest.new('http://stackoverflow.com/').get
request.callback do
puts request.response
EventMachine.stop
end
end
还有一个用于并行发出许多请求的接口,类似于 Typhoeus Hydra.
There's also an interface for making many requests in parallel, similarly to Typhoeus Hydra.
em-http-request 的缺点是它与 EventMachine 绑定.EventMachine 本身就是一个很棒的框架,但它是一个孤注一掷的交易.您需要以事件/持续传递风格的方式编写整个应用程序,并且已知这会导致脑损伤.Typhoeus 更适合尚未发生事件的应用程序.
The downside of em-http-request is that it is tied to EventMachine. EventMachine is an awesome framework in itself, but it's an all-or-nothing deal. You need to write your whole application in an evented/continuation-passing-style fashion, and that has been known to cause brain damage. Typhoeus is much better suited to applications that are not already evented.
这篇关于在 Ruby 中执行非阻塞 I/O 的首选方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!