Fas*_*ish 8 ruby rubygems nonblocking
如果说我想检索一个网页进行解析,但是在I/O发生时不阻塞CPU.有没有相当于Python的Eventlet库的东西?
The*_*heo 17
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
Run Code Online (Sandbox Code Playgroud)
另一个选项是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
Run Code Online (Sandbox Code Playgroud)
与Typhoeus Hydra类似,还有一个用于并行发出许多请求的界面.
em-http-request的缺点是它与EventMachine绑定在一起.EventMachine本身就是一个很棒的框架,但它是一个全有或全无的交易.你需要以一种正确/持续传递的方式编写你的整个应用程序,并且已知会导致脑损伤.Typhoeus更适合尚未使用的应用程序.
| 归档时间: |
|
| 查看次数: |
4022 次 |
| 最近记录: |