Ruby http/net 中连接超时问题

后端开发   发布日期:2025年07月28日   浏览次数:266

下面在调用币安的接口时,经常会卡住,设置连接超时也不会抛出异常,代码如下(默认连接超时为nil, 参考:https://github.com/ruby/ruby/pull/269):

require 'net/http'
require 'json'
require 'byebug'
uri = URI('https://www.binance.com/api/v1/ticker/24hr?symbol=EOSBTC')
req = Net::HTTP::Get.new(uri)
loop do
  res = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => uri.scheme == 'https') do |http|
    http.open_timeout = 1
    http.request(req)
  end
  puts "#{JSON.parse res.body}"
  puts "http request complete."
  sleep 1
end

不知道为什么,用 http.open_timeout = 1 这种设置不奏效,改为在start的options中配置即可则会超时抛出异常,如下:

  res = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => uri.scheme == 'https', :open_timeout => 1) do |http|
    http.request(req)
  end

以上就是Ruby http/net 中连接超时问题的详细内容,更多关于Ruby http/net 中连接超时问题的资料请关注九品源码其它相关文章!