如何在Heroku中执行并行HTTP请求? [英] How to do parallel HTTP requests in Heroku?

查看:122
本文介绍了如何在Heroku中执行并行HTTP请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我构建了一个Ruby on Rails应用程序,它可以访问6-7个API,根据用户的输入从它们中获取信息,比较和显示结果给用户(信息不保存在数据库中)。我将使用Heroku来部署应用程序。我希望这些HTTP请求能够并行访问API,因此回答时间会更好,而不是顺序执行。你认为在Heroku中实现这个目标的最好方法是什么?



非常感谢您的任何建议!

如果你想在服务器端实际做请求(tfe的javascript解决方案是个好主意),你最好的选择就是使用 EventMachine的。使用EventMachine提供了一种简单的方法来执行非阻塞IO。



另外检查 EM-Synchrony ,用于一套Ruby 1.9光纤感知客户端(包括HTTP)。



所有您需要做的非阻塞HTTP请求是例如:

 需要em-synchrony
需要em-synchrony / em-http
EM.synchrony do
concurrency = 2
url = ['http://url.1.com','http://url2.com']

#迭代器将执行异步块直到完成,.each,.inject也可以工作!
results = EM :: Synchrony :: Iterator.new(urls,concurrency).map do | url,iter |

#发出异步请求,在完成时提前迭代器
http = EventMachine :: HttpRequest.new(url).aget
http.callback {iter.return(http)}
http.errback {iter.return(http)}
结束

p结果#全部完成请求
EventMachine.stop
结束

好运!


I'm building a Ruby on Rails app that access about 6-7 APIs, grabs information from them based on user's input, compares and display results to the users (the information is not saved in the database). I will be using Heroku to deploy the app. I would like those HTTP requests to access the APIs to be done in parallel so the answer time is better instead of doing it sequential. What do you think is the best way to achieve this in Heroku?

Thank you very much for any suggestions!

解决方案

If you want to actually do the requests on the server side (tfe's javascript solution is a good idea), your best bet would be using EventMachine. Using EventMachine gives a simple way to do non-blocking IO.

Also check out EM-Synchrony for a set of Ruby 1.9 fiber aware clients (including HTTP).

All you need to do for a non-blocking HTTP request is something like:

require "em-synchrony"
require "em-synchrony/em-http"
EM.synchrony do
    concurrency = 2
    urls = ['http://url.1.com', 'http://url2.com']

    # iterator will execute async blocks until completion, .each, .inject also work!
    results = EM::Synchrony::Iterator.new(urls, concurrency).map do |url, iter|

        # fire async requests, on completion advance the iterator
        http = EventMachine::HttpRequest.new(url).aget
        http.callback { iter.return(http) }
        http.errback { iter.return(http) }
    end

    p results # all completed requests
    EventMachine.stop
end

Goodluck!

这篇关于如何在Heroku中执行并行HTTP请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆