【问题标题】:EM-HTTP-REQUEST and SINATRA - combining/merging multiple api request into one result?EM-HTTP-REQUEST 和 SINATRA - 将多个 api 请求组合/合并为一个结果?
【发布时间】:2013-11-06 09:19:03
【问题描述】:

我第一次处理 sinatra 和并行 em-http-request。而且我不知道如何组合/合并为一个结果以及何时使用 EventMachine.stop? .考虑一下:

get '/data/:query' do
  content_type :json

  EventMachine.run do
    http1 = EventMachine::HttpRequest.new('v1/').get
    http2 = EventMachine::HttpRequest.new('v2/').get

    http1.errback { p 'Uh oh nooooooo'; EventMachine.stop }

    http1.callback {
     // do some operation http1.repsonse
     Crack::XML.parse(http1.response).to_json
      EventMachine.stop
    }

    http2.callback {
     // do some operation http2.response
     Crack::XML.parse(http2.response).to_json
     EventMachine.stop
    } 

  end

  somehow merge 
  return merged_result

end

【问题讨论】:

    标签: json sinatra em-http-request


    【解决方案1】:

    上面的示例有一个竞争条件 - 一旦其中一个请求完成,您就会停止事件循环。为了解决这个问题,您可以使用内置的“Multi”界面:

    EventMachine.run do
      multi = EventMachine::MultiRequest.new
    
      multi.add :google, EventMachine::HttpRequest.new('http://www.google.com/').get
      multi.add :yahoo, EventMachine::HttpRequest.new('http://www.yahoo.com/').get
    
      multi.callback do
        puts multi.responses[:callback]
        puts multi.responses[:errback]
        EventMachine.stop
      end
    end
    

    查看 em-http wiki 页面了解更多信息:https://github.com/igrigorik/em-http-request/wiki/Parallel-Requests#synchronizing-with-multi-interface

    【讨论】:

    • 感谢您回到我身边。我可以要求你更加冗长和耐心吗?如何分别解析和响应来自 google 和 yahooo 并对它们中的每一个执行不同的操作?之后合并它们并将这个合并的产品作为 sinatra 的响应返回?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-11
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    • 2013-08-15
    相关资源
    最近更新 更多