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
这段代码可以作为过程式代码运行,我只是想访问服务器,无需关心顺序。如何在ruby中实现呢?其中一种选择是使用线程。
以下是使用线程的示例:
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
有更好的解决方案吗..??
顺便说一句,我想调用mixpanel,所以我只想发出一个HTTP请求而不等待响应。