我在尝试连接的主机不总是可用的地方遇到麻烦。我在连接到主机的地方使用了这段代码:
begin #To catch error from Net::HTTP
net = Net::HTTP.new(uri.host, uri.port)
net.read_timeout = 5
net.continue_timeout = 5
res = net.start {|http|
http_request = http.request(req)
case http_request.response
case
...
else
@error_msg = "Response not handled by appliaction" << http_request.code << " " << http_request.message
end
}
rescue SocketError => se
@error_msg = "Net::SocketError #{se} (Perhaps host is down?)"
puts @error_msg
end
问题是当主机没有响应(或其他错误)时,连接似乎正在运行很长时间。我原本希望等待5秒钟,但尝试的时间太长了:
Completed 500 Internal Server Error in 126302ms
Errno::ETIMEDOUT - Connection timed out - connect(2):
如何设置Net:HTTP对象的最大超时时间?
谢谢
正如Ascar指出的那样,这是错误的语法。但是::read_timeout本身并不能解决问题,如果主机根本没有响应,我还需要添加:open_timeout。
Net::HTTP.start(uri.host, uri.port, {read_timeout: 5, open_timeout: 5})
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句