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

前端之家收集整理的这篇文章主要介绍了在Ruby中执行非阻塞I / O的首选方法是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果说我想检索一个网页进行解析,但是在I / O发生时不阻塞cpu.有没有相当于Python的Eventlet库的东西?

解决方法

Ruby的最佳HTTP客户端库是 Typhoeus,它可以用于以非阻塞方式并行执行多个HTTP请求.有一个阻塞和非阻塞接口:
  1. # blocking
  2. response = Typhoeus::Request.get("http://stackoverflow.com/")
  3. puts response.body
  4.  
  5. # non-blocking
  6. request1 = Typhoeus::Request.new("http://stackoverflow.com/")
  7. request1.on_complete do |response|
  8. puts response.body
  9. end
  10. request2 = Typhoeus::Request.new("http://stackoverflow.com/questions")
  11. request2.on_complete do |response|
  12. puts response.body
  13. end
  14. hydra = Typhoeus::Hydra.new
  15. hydra.queue(request1)
  16. hydra.queue(request2)
  17. hydra.run # this call is blocking,though

另一种选择是em-http-request,它运行在EventMachine之上.它有一个完全无阻塞的界面:

  1. EventMachine.run do
  2. request = EventMachine::HttpRequest.new('http://stackoverflow.com/').get
  3. request.callback do
  4. puts request.response
  5. EventMachine.stop
  6. end
  7. end

与Typhoeus Hydra类似,还有一个用于并行发出许多请求的界面.

em-http-request的缺点是它与EventMachine绑定. EventMachine本身就是一个很棒的框架,但它是一个全有或全无的交易.你需要以一种平衡/延续传递方式编写整个应用程序,并且已知这会导致脑损伤. Typhoeus更适合尚未使用的应用程序.

猜你在找的Ruby相关文章