gpt4 book ai didi

ruby-on-rails - 来自 Rails Controller 操作的并行请求

转载 作者:可可西里 更新时间:2023-11-01 16:18:40 26 4
gpt4 key购买 nike

我有一个用例,当 Controller 的一个 Action 被调用时,它会触发 3 个对其他 url 的 http 请求。我需要解析这些请求的响应,将它们组合起来然后呈现 View 。如何并行而不是顺序触发 3 个请求以节省时间?

最佳答案

我使用 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

关于ruby-on-rails - 来自 Rails Controller 操作的并行请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13775224/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com