开发者

Making a non blocking HTTP request in a Rails app

开发者 https://www.devze.com 2023-04-11 22:03 出处:网络
Is anyone aware of a way to make outgoing non blocking HTTP requests from within Rails?I 开发者_如何学JAVAwill need the response body eventually and am trying to avoid bringing up new frameworks to ke

Is anyone aware of a way to make outgoing non blocking HTTP requests from within Rails? I 开发者_如何学JAVAwill need the response body eventually and am trying to avoid bringing up new frameworks to keep things simple.

Thanks


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号