在队列中添加要获取的图像,然后抓取它们



我对ruby多线程相当陌生,对如何开始感到困惑。我目前正在建设一个应用程序,它需要获取大量的图像,所以我想在一个不同的线程。我希望程序按照下面的代码执行。

问题:我在这里看到的问题是,bar_method将完成抓取更快,线程将结束,所以事情将继续被添加到队列中,但不会被处理。是否有任何可能的同步方式,将提醒bar_method线程,一个新的项目已被添加到队列,如果bar_method完成较早,它应该去睡眠,等待一个新的项目被添加到队列?

def foo_method 
  queue created - consists of url to fetch and a callback method
  synch = Mutex.new
  Thread.new do
    bar_method synch, queue 
  end
  100000.times do
    synch.synchronize do
      queue << {url => img_url, method_callback => the_callback}
    end
  end
end
def bar_method synch_obj, queue
  synch_obj.synchronize do
    while queue isn't empty
        pop the queue. fetch image and call the callback
    end   
  end
end 

如果您需要从互联网检索文件,并使用并行请求,我将强烈推荐Typhoeus和Hydra。

来自文档:

hydra = Typhoeus::Hydra.new
10.times.map{ hydra.queue(Typhoeus::Request.new("www.example.com", followlocation: true)) }
hydra.run

可以设置Hydra的并发连接数:

:max_concurrency (Integer) -创建的最大并发连接数。默认值为200。

作为第二个建议,请查看约束。同样,从它的文档中:

# make multiple GET requests
easy_options = {:follow_location => true}
multi_options = {:pipeline => true}
Curl::Multi.get('url1','url2','url3','url4','url5', easy_options, multi_options) do|easy|
  # do something interesting with the easy response
  puts easy.last_effective_url
end

两者都建立在Curl之上,因此它们的底层技术或健壮性没有真正的区别。不同之处在于您可以使用的命令。

另一个获得大量关注的gem是EventMachine。它有EM-HTTP-Request,允许并发请求:

EventMachine.run {
  http1 = EventMachine::HttpRequest.new('http://google.com/').get
  http2 = EventMachine::HttpRequest.new('http://yahoo.com/').get
  http1.callback { }
  http2.callback { } 
end

最新更新