0

我第一次处理 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
4

1 回答 1

3

Above example has a race condition - you'll stop the eventloop as soon as one of the requests has finished. To address this, you can use the built in "Multi" interface:

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

See em-http wiki page for more: https://github.com/igrigorik/em-http-request/wiki/Parallel-Requests#synchronizing-with-multi-interface

于 2013-11-06T16:02:05.287 回答