在Ruby中执行非阻塞I / O的首选方式是什么? [英] What is the preferred way of performing non blocking I/O in Ruby?

查看:161
本文介绍了在Ruby中执行非阻塞I / O的首选方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

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

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

#非阻塞
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#此通话被屏蔽,但

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

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

还有一个可以并行处理多个请求的界面,类似于Typhoeus Hydra。



em-http-request的缺点是它与EventMachine绑定在一起。 EventMachine本身就是一个很棒的框架,但它是一个全有或全无的交易。你需要以整齐的/延续传递式的方式编写你的整个应用程序,并且这已被认为会造成脑损伤。 Typhoeus更适合于尚未完成的应用程序。

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?

解决方案

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

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

There's also an interface for making many requests in parallel, similarly to Typhoeus Hydra.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆