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

如果说我想检索一个网页进行解析,但是在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 

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

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

我不确定Eventlet是做什么的,但Ruby有EventMachine ,一个非阻塞IO的库( 除此之外 )。