Making a non blocking HTTP request in a Rails app
Asked Answered
F

3

7

Is anyone aware of a way to make outgoing non blocking HTTP requests from within Rails? I will need the response body eventually and am trying to avoid bringing up new frameworks to keep things simple.

Thanks

Familiarize answered 11/10, 2011 at 2:8 Comment(1)
Possible duplicate of What is the preferred way of performing non blocking I/O in Ruby?Cyr
S
0

You can do something like this:

def async_post
  Thread.new do
    uri = URI('https://somewhere.com/do_something')
    response = Net::HTTP.post_form(uri, 'param1' => '1', 'param2' => '2')
    # do something with the response
  end
  # Execution continues before the response is received
end
Serf answered 15/11, 2023 at 17:33 Comment(0)
A
-1

To simulate the non-blocking part, set a low read_timeout. Also be prepared to catch the resulting timeout error:

request = Net::HTTP::Get.new(url)
http = Net::HTTP.new(url.host, url.port)

http.read_timeout = 1

begin
  http.request(request)
rescue Timeout::Error => e
end

I don't know of a basic rails mechanism that will both make a non-blocking call and receive the response. Rails is very much tied to the request/response cycle, so usually the basic controller execution path will have ended before the HTTP call returns.

Archlute answered 21/3, 2012 at 1:28 Comment(2)
"low timeout" != "non-blocking"Bridgers
Absolutely nothing about a low timeout "simulates" non-blocking IO. Now you're doing blocking IO with tons of timeouts and failed requests, the worst of all worlds.Agitprop
M
-2

You're looking for "background jobs" or "background workers." There are a variety of gems for this. This blog post has a good overview of what's out there. delayed_job is very popular right now.

Mephitis answered 11/10, 2011 at 2:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.