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
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
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
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.
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.
© 2022 - 2024 — McMap. All rights reserved.