use*_*990 2 ruby ruby-on-rails ruby-on-rails-3.1 ruby-2.0 ruby-on-rails-4
我在ruby中创建API.
正在调查异步请求,阻塞方法,如等待异步操作..
任何人都可以建议哪种方法可以处理API的异步操作
您可以使用Typhoeus gem来构建并行运行HTTP请求.
我们的想法是使用块准备多个请求,以处理每个请求的成功/错误,然后并行运行所有请求."运行阶段"将阻止,直到所有请求都完成.
以下是项目页面中的示例:
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
Run Code Online (Sandbox Code Playgroud)
如果你不想等待你的异步操作结束(但你的问题另有说明)那么它有点复杂:你应该有一个API来运行请求并将一个请求ID返回给调用者,这可能是稍后查询API以获得与其收到的请求ID相关联的结果.
为了更灵活,您可以使用Faraday,这是一个HTTP客户端库,为多个后端提供统一的接口.从您喜欢的任何后端开始,如果您想测试/提高性能,您应该可以稍后将适配器更改为另一个.
Typhoeus提供法拉第后端,但您也可以使用基于EventMachine的EM-HTTP-Request,这是一个着名的宝石.您可以使用带有法拉第和EM-Synchrony的Ruby的Fibers,如本例所示.
以下是使用Faraday和Typhoeus运行并行请求的示例:https://github.com/lostisland/faraday/wiki/Parallel-requests
使用前面的示例,应该很容易适应使用EM-HTTP请求适配器.
| 归档时间: |
|
| 查看次数: |
1637 次 |
| 最近记录: |