Note that there are some explanatory texts on larger screens.

plurals
  1. POMultiple http requests on the same long running operation with Sinatra and EventMachine
    primarykey
    data
    text
    <p>I'm trying to understand how to use evented web servers with a combination of async sinatra and EventMachine. </p> <p>In the code below each request on '/' will generate a new async http request to google. Is there an elegant solution for detecting that a request is already ongoing and waiting for its execution ? </p> <p>If I have 100 concurrent requests on '/', this will generate 100 requests to the google backend. It would be much better to have a way to detect there is already an ongoing backend request and wait for its execution.</p> <p>thanks for the answer.</p> <pre><code>require 'sinatra' require 'json' require 'eventmachine' require 'em-http-request' require 'sinatra/async' Sinatra.register Sinatra::Async def get_data puts "Start request" http = EventMachine::HttpRequest.new("http://www.google.com").get http.callback { puts "Request completed" yield http.response } end aget '/' do get_data {|data| body data} end </code></pre> <p><strong>Update</strong></p> <p>I actually discovered you can add several callbacks to the same http request. So, it's easy to implement: </p> <pre><code>class Request def get_data if !@http || @http.response_header.status != 0 #puts "Creating new request" @http = EventMachine::HttpRequest.new("http://www.bbc.com").get end #puts "Adding callback" @http.callback do #puts "Request completed" yield @http.response end end end $req = Request.new aget '/' do $req.get_data {|data| body data} end </code></pre> <p>This gives a very high number of requests per second. Cool!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload