Ruby on Rails同时有多个HTTP请求?

时间:2013-04-17 03:24:40

标签: ruby-on-rails ruby multithreading httprequest instagram

我正在提出多个请求(一次拉一个请求),我想知道如果我有这样的话,是否有同时拉取请求的方式:

client = Instagram.client(:access_token => session[:access_token])
@user = client.user
@recent_media_items = client.user_recent_media

@lv = client.tag_recent_media('lv', options = {:count => 60})
@lv1 = client.tag_recent_media('lv1', options = {:count => 60})
@lv2 = client.tag_recent_media('lv2', options = {:count => 60})
@lv3 = client.tag_recent_media('lv3', options = {:count => 60})

每个lvclient发出请求。我想知道是否有办法这样做,所以它可以一次性(一起)完成请求,而不是一个完成请求,然后继续下一个请求,等等......

谢谢!

2 个答案:

答案 0 :(得分:12)

是的!要获得概念验证,请尝试

require 'thread'

client = Instagram.client(:access_token => session[:access_token])
@user = client.user
@recent_media_items = client.user_recent_media

threads = []
threads << Thread.new { @lv = client.tag_recent_media('lv', options = {:count => 60}) }
threads << Thread.new { @lv1 = client.tag_recent_media('lv1', options = {:count => 60}) }
threads << Thread.new { @lv2 = client.tag_recent_media('lv2', options = {:count => 60}) }
threads << Thread.new { @lv3 = client.tag_recent_media('lv3', options = {:count => 60}) }
threads.each(&:join) # this waits for all the threads to finish before proceeding
puts [@lv, @lv1, @lv2, @lv3]

实际上,您需要在线程中设置一些错误处理和重试设置。此外,您可能会在Instagram gem中遇到线程安全问题。如果您大规模地执行此操作有数百或数千个请求,您可能需要尝试并发HTTP客户端(如Typhoeus)或偶然HTTP客户端(如EM-HTTP-Request)。对于这些,您必须手动实现Instagram gem中的tag_recent_media方法。

答案 1 :(得分:4)

像spawn这样的宝石可以在分叉的过程中执行此操作,也可以作为流程中的新线程。这是指向另一个讨论它的SO帖子的链接

What is the difference between forking and threading in a background process?

以下是有问题的宝石:https://github.com/tra/spawnling