gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 06:51:46 25 4
gpt4 key购买 nike

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

最佳答案

Ruby 的最佳 HTTP 客户端库是 Typhoeus ,它可用于以非阻塞方式并行执行多个 HTTP 请求。有阻塞和非阻塞接口(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

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

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

还有一个接口(interface)可以并行发出许多请求,类似于 Typhoeus Hydra。

em-http-request 的缺点是它绑定(bind)到 EventMachine。 EventMachine 本身就是一个很棒的框架,但它是一个孤注一掷的交易。您需要以事件/连续传递风格的方式编写整个应用程序,众所周知,这会导致脑损伤。 Typhoeus 更适合尚未发生事件的应用程序。

关于ruby - 在 Ruby 中执行非阻塞 I/O 的首选方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4468471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com