【发布时间】: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...