ruby-on-rails – Ruby on Rails同时有多个HTTP请求?

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – Ruby on Rails同时有多个HTTP请求?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在拉多个请求(它一次拉一个),我想知道如果我有这样的东西,是否有一种方式同时拉请求所有:
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})

每个lv向客户提出请求.我想知道是否有办法这样做,所以它可以一次性(一起)完成请求,而不是一个完成请求,然后继续下一个请求,依此类推……

谢谢!

解决方法

是!对于概念验证,请尝试
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中的线程安全问题.如果您正在大规模地执行此操作,有数百或数千个请求,您可能需要尝试像Typhoeus这样的并发HTTP客户端或像EM-HTTP-Request这样的偶然HTTP客户端.对于这些,您必须手动实现其中的tag_recent_media方法. Instagram的宝石.

猜你在找的Ruby相关文章