ruby中的异步http请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6643964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:33:45  来源:igfitidea点击:

asynchronous http request in ruby

ruby-on-railsrubyruby-on-rails-3httpmixpanel

提问by Mohit Jain

 require 'net/http'

urls = [
  {'link' => 'http://www.google.com/'},
  {'link' => 'http://www.facebook.com/'},
 {'link' => 'http://www.yahoo.com/'}
]

urls.each do |u|
  u['content'] = Net::HTTP.get( URI.parse(u['link']) )
end

print urls

This will work as procedural code.. I just want to hit a server, no issues about the order. How can i do that in ruby. One option is using threads.

这将作为程序代码工作..我只想打一个服务器,订单没有问题。我怎么能在 ruby​​ 中做到这一点。一种选择是使用线程。

Here's an example using threads.

这是使用线程的示例。

require 'net/http'

urls = [
  {'link' => 'http://www.google.com/'},
  {'link' => 'http://www.facebook.com/'},
  {'link' => 'http://www.yahoo.com/'}
]

urls.each do |u|
  Thread.new do
    u['content'] = Net::HTTP.get( URI.parse(u['link']) )
    puts "Successfully requested #{u['link']}"

    if urls.all? {|u| u.has_key?("content") }
      puts "Fetched all urls!"
      exit
    end
  end
end

Any better solution..??

有什么更好的解决方案吗??

PS:- i want to hit mixpanel, so that's why I just want to make a http call and dont wait for the response.

PS:-我想点击mixpanel,所以这就是为什么我只想进行http调用而不等待响应。

采纳答案by apneadiving

Lightweight Async handling is the job of Threads (as you said) or Fibers.

轻量级异步处理是 Threads (如您所说)或Fibers 的工作

Otherwise, you should consider EventMachinewhich is a very powerful tool.

否则,您应该考虑EventMachine,这是一个非常强大的工具。

EDIT: The above URL for Event Machine is dead. Here is their GitHub account, https://github.com/eventmachine/eventmachine. It serves as a good starting point.

编辑:上面的事件机 URL 已失效。这是他们的 GitHub 帐户,https://github.com/eventmachine/eventmachine。它是一个很好的起点。

回答by emboss

Here is a great articlecovering the topic.

这是一篇涵盖该主题的精彩文章

Generally, viable alternatives to using threads for this would be the use of a Fiberor you could use em-http-request. In the latter example you could leave out the callback handling for your particular purpose.

通常,为此使用线程的可行替代方案是使用Fiber或者您可以使用em-http-request。在后一个示例中,您可以出于特定目的省略回调处理。

回答by Sumit Malik

If its just about plain http requests in async style, probably Unirestis the best fit to achieve it.

如果它只是异步风格的普通 http 请求,那么 Unirest可能最适合实现它。

Asnc request is as simple as:

Asnc 请求非常简单:

response = Unirest.post "http://httpbin.org/post", 
                    headers:{ "Accept" => "application/json" }, 
                    parameters:{ :age => 23, :foo => "bar" } {|response|
response.code # Status code
response.headers # Response headers
response.body # Parsed body
response.raw_body # Unparsed body
}