为什么我们在使用net/http时需要运行start



如果我使用:

uri = URI("...")
http = Net::HTTP.new(uri.host, uri.port)
http.read_timeout = 60
# Add http.start here? Why?
for i in 1..n
uri = getFullUri()
req = Net::HTTP::Get.new(uri.path)
resp = http.request(req)
end

一切都很好。

为什么我需要添加http.start

我看到如果我不添加http.starthttp.started?到处都会返回false,但这会产生负面影响吗?

这两种情况之间的区别是什么?

TCP连接或HTTP会话的数量不同吗?

http.start()将在调用TCP连接的时间点显式打开该连接。如果它还没有被调用,http.request()会自动调用它。也就是说,这里是request方法的前几行:

def request(req, body = nil, &block)  # :yield: +response+
unless started?
start {
req['connection'] ||= 'close'
return request(req, body, &block)
}
end

假设getFullUri()的运行时间不到几秒钟(请参阅keep_alive_timeout属性(,那么无论原始连接是如何创建的,都应该重用它。

相关内容

最新更新