制作多个HTTP请求异步
问题描述:
require 'net/http'
urls = [
{'link' => 'http://www.google.com/'},
{'link' => 'http://www.yandex.ru/'},
{'link' => 'http://www.baidu.com/'}
]
urls.each do |u|
u['content'] = Net::HTTP.get( URI.parse(u['link']) )
end
print urls
这code工作在同步风格。第一个要求,第二,第三。我想异步发送的所有请求,并打印网址
后,所有的人就完成了。
This code works in synchronous style. First request, second, third. I would like to send all requests asynchronously and print urls
after all of them is done.
什么是最好的方式做到这一点?光纤是适合的?
What the best way to do it? Is Fiber suited for that?
答
下面是使用线程的例子。
Here's an example using threads.
require 'net/http'
urls = [
{'link' => 'http://www.google.com/'},
{'link' => 'http://www.yandex.ru/'},
{'link' => 'http://www.baidu.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
sleep