Making multiple HTTP requests asynchronously

后端 未结 8 1163
傲寒
傲寒 2020-12-13 21:44
require \'net/http\'

urls = [
  {\'link\' => \'http://www.google.com/\'},
  {\'link\' => \'http://www.yandex.ru/\'},
  {\'link\' => \'http://www.baidu.com/\'}
]

ur         


        
相关标签:
8条回答
  • 2020-12-13 22:47

    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
    
    0 讨论(0)
  • 2020-12-13 22:47

    It depends what you want to do after the function afterwards. You can do it with simple threads:

    see: http://snipplr.com/view/3966/simple-example-of-threading-in-ruby/

    0 讨论(0)
提交回复
热议问题