我想在下面的代码中看到使用Benchmark
访问网址所需的时间。我也试图在没有基准的情况下做同样的事情。也就是说,在测试开始和测试结束时获取时间,减去两个以获得时间。两种方法都以相同的超时错误结束。
require 'open-uri'
require 'benchmark'
response = nil
puts "opening website with benchmark..."
puts Benchmark.measure{
response = open('http://mywebsite.com')
}
puts "Done !"
status = response.status
puts status
错误:
opening website with benchmark...
C:/ruby/lib/ruby/1.8/timeout.rb:64:in `rbuf_fill': execution expired (Timeout::Error)
from C:/ruby/lib/ruby/1.8/net/protocol.rb:134:in `rbuf_fill'
from C:/ruby/lib/ruby/1.8/net/protocol.rb:116:in `readuntil'
from C:/ruby/lib/ruby/1.8/net/protocol.rb:126:in `readline'
from C:/ruby/lib/ruby/1.8/net/http.rb:2028:in `read_status_line'
from C:/ruby/lib/ruby/1.8/net/http.rb:2017:in `read_new'
from C:/ruby/lib/ruby/1.8/net/http.rb:1051:in `request'
from C:/ruby/lib/ruby/1.8/open-uri.rb:248:in `open_http'
from C:/ruby/lib/ruby/1.8/net/http.rb:543:in `start'
from C:/ruby/lib/ruby/1.8/open-uri.rb:242:in `open_http'
from C:/ruby/lib/ruby/1.8/open-uri.rb:616:in `buffer_open'
from C:/ruby/lib/ruby/1.8/open-uri.rb:164:in `open_loop'
from C:/ruby/lib/ruby/1.8/open-uri.rb:162:in `catch'
from C:/ruby/lib/ruby/1.8/open-uri.rb:162:in `open_loop'
from C:/ruby/lib/ruby/1.8/open-uri.rb:132:in `open_uri'
from C:/ruby/lib/ruby/1.8/open-uri.rb:518:in `open'
from C:/ruby/lib/ruby/1.8/open-uri.rb:30:in `open'
from C:/code/test.rb:7
from C:/ruby/lib/ruby/1.8/benchmark.rb:293:in `measure'
from C:/code/test.rb:6
当我尝试在浏览器中连接到此URL时,始终需要大约2-3分钟才能访问。
我搜索了谷歌,但发现我的问题没有有用的答案。我知道我必须这样做 更改某些内容的超时设置,但无法确定哪一个。有人可以帮忙吗?
答案 0 :(得分:14)
使用以秒为单位指定的:read_timeout
选项,例如,
open('foo.com', :read_timeout => 10)
http://ruby-doc.org/stdlib-1.8.7/libdoc/open-uri/rdoc/OpenURI/OpenRead.html
答案 1 :(得分:2)
BufferedIO
Net::HTTP
用于open-uri
用于请求的连接的Net::HTTP
类具有read_timeout
attribute set to 60 seconds。
open-uri
课程提供setter read_timeout
for that。
不幸的是,60
sets up请求的方式无法为您提供在请求之前获取该设置的方法,或者轻松覆盖默认的Net::HTTP
。
您可能需要自己使用link = URI.parse(url)
request = Net::HTTP::Get.new(link.path)
response = Net::HTTP.start(link.host, link.port) {|http|
http.read_timeout = 100 #Default is 60 seconds
http.request(request)
}
。
:read_timeout = x
代码从this answer
被盗编辑:或升级到1.9,支持{{1}}选项Dave Newton指出。