Making multiple HTTP requests asynchronously

后端 未结 8 1161
傲寒
傲寒 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:45

    The work_queue gem is the easiest way to perform tasks asynchronously and concurrently in your application.

    wq = WorkQueue.new 2 # Limit the maximum number of simultaneous worker threads
    
    urls.each do |url|
      wq.enqueue_b do
        response = Net::HTTP.get_response(url)
        # use the response
      end
    end
    
    wq.join # All requests are complete after this
    

提交回复
热议问题