Ruby on Rails同时存在多个HTTP请求吗? [英] Ruby on Rails Multiple HTTP request at the same time?
问题描述
我要拉多个请求(一次拉一个),我想知道是否有一种方法可以同时拉所有请求:
I'm pulling multiple requests (its pulling one at a time), I was wondering if there's a way pull requests all at the same time if I have something like this:
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
向client
发出请求.我想知道是否有办法做到(一次)一起完成所有请求,而不是一次完成请求,然后继续下一个请求,依此类推...
Each lv
makes a request to client
. I was wondering if there's a way to do such so it can do the request all at once (together), instead of one finishes the request, then goes on to the next request, and so on...
谢谢!
推荐答案
是的!要进行概念验证,请尝试
Yes! For a proof-of-concept, try
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客户端,或者事件HTTP客户端,例如 EM-HTTP-Request .对于这些,您将必须手动实现Instagram gem中的tag_recent_media
方法.
In practice, you will want to set up some error handling and retry settings within the threads. Also, you may run into issues with thread-safety in the Instagram gem. If you are doing this on a large scale with hundreds or thousands of requests, you may want to try a concurrent HTTP client like Typhoeus or an evented HTTP client like EM-HTTP-Request. For these, you would have to manually implement the tag_recent_media
method that is in the Instagram gem.
这篇关于Ruby on Rails同时存在多个HTTP请求吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!