在 Rails 应用程序中发出非阻塞 HTTP 请求

发布于 2024-12-08 21:43:50 字数 78 浏览 0 评论 0原文

有谁知道如何从 Rails 中发出非阻塞 HTTP 请求?我最终将需要响应主体,并试图避免提出新的框架以使事情变得简单。

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

红焚 2024-12-15 21:43:50

你可以这样做:

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

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
丢了幸福的猪 2024-12-15 21:43:50

这不是非阻塞的,但你可以设置一个非常低的read_timeout。还要捕获由此产生的超时错误,这本身就是一个小的性能损失:

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

我不知道有什么基本的 Rails 机制可以发出非阻塞调用并接收响应。 Rails 与请求/响应周期密切相关,因此通常基本控制器执行路径将在 HTTP 调用返回之前结束。

This is not non-blocking, but you can set a very low read_timeout. Also catch the resulting timeout error, which itself is a small perf penalty:

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.

虫児飞 2024-12-15 21:43:50

您正在寻找“后台工作”或“后台工人”。为此有各种各样的宝石。 这篇博文有一个很好的内容那里有什么的概述。 delayed_job 现在非常流行。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文