如何在 ruby API 中创建异步请求、阻塞方法

How to create async requests, blocker methods in ruby API

我正在 ruby 中创建 API。

正在研究异步请求、等待异步操作等阻塞方法..

任何人都可以建议哪种方法是处理 API

的异步操作的最佳方法

您可以使用 Typhoeus gem,它是为并行 运行 HTTP 请求构建的。

我们的想法是准备几个带有块的请求,用于处理每个请求的 success/error,然后并行地 运行 所有这些请求。 "run phase" 将阻塞,直到所有请求完成。

这是项目页面中的示例:

hydra = Typhoeus::Hydra.hydra

first_request = Typhoeus::Request.new("http://example.com/posts/1")
first_request.on_complete do |response|
  third_url = response.body
  third_request = Typhoeus::Request.new(third_url)
  hydra.queue third_request
end
second_request = Typhoeus::Request.new("http://example.com/posts/2")

hydra.queue first_request
hydra.queue second_request
hydra.run # this is a blocking call that returns once all requests are complete

如果您不想等待异步操作结束(但您的问题另有说明)那么它会稍微复杂一些:您应该有一个 API 到 运行请求和 return 调用方的请求 ID,调用方稍后可以查询 API 以获取与其收到的请求 ID 关联的结果。

为了更灵活一点,您可以使用 Faraday,一个为多个后端提供统一接口的 HTTP 客户端库。从您喜欢的任何后端开始,如果您想要 test/improve 性能,以后应该可以将适配器更改为另一个。

Typhoeus 提供法拉第后端,但您也可以使用 EM-HTTP-Request which is based on EventMachine, a well-known gem. You can leverage Ruby's Fibers with Faraday and EM-Synchrony as shown in this example

这是一个示例 运行ning 与 Faraday 和 Typhoeus 的并行请求:https://github.com/lostisland/faraday/wiki/Parallel-requests

使用前面的示例,应该很容易适应使用 EM-HTTP-request 适配器。