Skip to content

Persistent Connections (keep alive)

Marcello Barnaba edited this page Oct 11, 2020 · 6 revisions

If you need to make many successive requests against the same host, you can create client with persistent connection to the host:

begin
  # create HTTP client with persistent connection to api.icndb.com:
  http = HTTP.persistent "http://api.icndb.com"

  # issue multiple requests using same connection:
  jokes = 100.times.map { http.get("/jokes/random").to_s }
ensure
  # close underlying connection when you don't need it anymore
  http.close if http
end

If the optional code block is given, it will be passed the client with persistent connection to the host as an argument and client.close will be automatically called when the block terminates. The value of the block will be returned:

jokes = HTTP.persistent "http://api.icndb.com" do |http|
  100.times.map { http.get("/jokes/random").to_s }
end

NOTE: Using persistent requests correctly

You must consume response before sending next request via persistent connection. That means you need to call #to_s, #parse or #flush on response object. In the example above we used http.get("/jokes/random").to_s to get response bodies. That works perfectly fine, because #to_s reads off the response.

Sometimes you don't need response body, or need whole response object to access its status, headers etc instead. You can either call #to_s to make sure response was flushed and then use response object itself, or use #flush (syntax sugar for #tap(&:to_s) that will do that for you:

contents = HTTP.persistent "http://en.wikipedia.org" do |http|
  %w(Hypertext_Transfer_Protocol Git GitHub Linux Hurd).map do |page|
    http.get("/wiki/#{page}").flush
  end
end

See Also

Clone this wiki locally