【问题标题】:HTTP: Is it necessary to close a connection with finish after opening a connection with new?HTTP:打开连接后是否需要关闭连接?
【发布时间】:2018-06-26 04:45:45
【问题描述】:

Ruby 核心附带的 Net::HTTP API 中有几种方法。有些像 Net::HTTP.get、Net::HTTP.get_response 和 Net::HTTP.post_form 不会持久连接。但是, ::start 和 ::new 确实保持连接。事实上,::start 需要一个块保持打开连接,直到块退出:

uri = URI("example.com")
Net::HTTP.start(uri.host, uri.port) do |http|
  response1 = http.get('path1')
  response2 = http.get('path2')
end

现在您可以使用 ::new 代替 ::start:

  http = Net::HTTP.new('example.com')
  http.start
  response1 = http.get('path1')
  response2 = http.get('path2')

但是我必须手动关闭连接吗?这是必需品还是我可以不使用它:

begin
  http = Net::HTTP.new('example.com')
  http.start
  response1 = http.get('path1')
  response2 = http.get('path2')
ensure
  http.finish
end

如果我跳过完成调用,这会在应用程序中造成某种膨胀或内存泄漏吗?

【问题讨论】:

  • http.start的块形式调用ensure; do_finish,finish调用do_finish。不过,似乎没有析构函数可以为您调用finish...

标签: ruby http


【解决方案1】:

根据文档,使用new 不会打开连接:

创建一个新的 Net::HTTP 对象而不打开 TCP 连接或 HTTP 会话。

但是要回答您的问题,是的,您应该在使用连接后关闭它们。连接最终会关闭,但是当您使用完自己的非托管资源后,不清理它们是一种不好的做法。

首选方法是您演示的方式,将start 与块一起使用,这可确保在块退出时连接将关闭。

编辑

我不够具体。我指的是类方法start,而不是实例方法start。类方法签名如下所示:

start(address, port, p_addr, p_port, p_user, p_pass, &block)
start(address, port=nil, p_addr=nil, p_port=nil, p_user=nil, p_pass=nil, opt, &block)

可以在here 找到它的文档,不过我相信你已经知道参数了。

【讨论】:

  • 但是如果 ::start 是首选方法,那么如何将 HTTP 参数传递给 ::start?比如use_ssl、verify_mode等
  • 我更新了我的答案,但不够具体。有一个类方法start,不是实例方法版本。类方法接受一个块和参数。
猜你喜欢
  • 2013-03-04
  • 1970-01-01
  • 2011-08-21
  • 2012-02-11
  • 2013-09-20
  • 1970-01-01
  • 1970-01-01
  • 2016-08-03
  • 1970-01-01
相关资源
最近更新 更多