如果我想要获取一个网页进行解析,但不想在I/O操作期间阻塞CPU。是否有类似于Python的Eventlet库的东西?
如果我想要获取一个网页进行解析,但不想在I/O操作期间阻塞CPU。是否有类似于Python的Eventlet库的东西?
最好的Ruby HTTP客户端库是Typhoeus,可以用于以非阻塞的方式并行执行多个HTTP请求。它具有阻塞和非阻塞接口:
# 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之上。它具有完全非阻塞的接口:
EventMachine.run do
request = EventMachine::HttpRequest.new('http://stackoverflow.com/').get
request.callback do
puts request.response
EventMachine.stop
end
end
em-http-request还提供了一个接口,可以并行发送多个请求,类似于Typhoeus Hydra。
em-http-request的缺点是它与EventMachine绑定。EventMachine本身是一个很棒的框架,但它是一个全盘承包的方案。你需要以事件/传递方式编写整个应用程序,这已经被证明会导致脑损伤。Typhoeus更适合不需要事件的应用程序。