来自rails控制器动作的并行请求

时间:2012-12-08 06:44:11

标签: ruby-on-rails api http response

我有一个用例,当调用控制器的动作时,它会触发对其他URL的3个http请求。我需要解析这些请求的响应,组合它们然后呈现视图。如何并行触发3个请求而不是按顺序触发请求以节省时间?

1 个答案:

答案 0 :(得分:2)

我使用Typhoes来处理并行调用。

跳转至making parallel calls部分,了解如何进行并行呼叫。

实施例

 # Assume these were your two HTTP calls
 first_request = Typhoes::Request.new('http://jsonplaceholder.typicode.com/posts?userId=2')
 second_request = Typhoes::Request.new('http://jsonplaceholder.typicode.com/posts?userId=3')

 # Initialize a Hydra queue (this holds typhoes requests)
 hydra = Typhoeus::Hydra.hydra
 hydra.queue [first_request, second_request]
 hydra.run # this triggers the calls

 # Getting response, once the run is complete

 first_request.response 
 second_request.response 
相关问题