ruby restclient 超时无法正常工作,它会在定义的超时时间加倍后抛出异常

ruby restclient timeout does not work properly, it throws exception after double the defined timeout

注意到 Ruby RestClient 没有精确地遵循给定的超时参数,但是它通过将当前超时设置加倍来工作。

有没有人注意到同样的情况?下面附上测试代码示例。

由于 httpbin.org 有最大延迟 10,我们需要使用小超时:

  def test_timeout(delay)
    start = Time.now.to_i
    RestClient::Request.execute(url:     "http://httpbin.org/delay/10",
                                method:  'GET',
                                timeout: delay)
    return 0
  rescue RestClient::Exceptions::ReadTimeout => exception
    endtime = Time.now.to_i
    return endtime - start
  end

pry(main)> test_timeout 1
RestClient.get "http://httpbin.org/delay/10", "Accept"=>"*/*", "Accept-Encoding"=>"gzip, deflate"

=> 3

pry(main)> test_timeout 5
RestClient.get "http://httpbin.org/delay/10", "Accept"=>"*/*", "Accept-Encoding"=>"gzip, deflate"

=> 10

使用 Ruby RestClient 2.0.2 并使用 2.1.0.rc1 进行测试

还使用 read_timeout 和 open_timeout 参数进行了测试,它们具有相同的

  def test_timeout(delay)
    start = Time.now.to_i
    RestClient::Request.execute(url: "http://httpbin.org/delay/10",
                                method: 'GET',
                                open_timeout: 1,
                                read_timeout: delay)
    return 0
  rescue RestClient::Exceptions::ReadTimeout => exception
    endtime = Time.now.to_i
    return endtime - start
  end

pry(main)> test_timeout 2
RestClient.get "http://httpbin.org/delay/10", "Accept"=>"*/*", "Accept-Encoding"=>"gzip, deflate"

=> 4
pry(main)> test_timeout 3
RestClient.get "http://httpbin.org/delay/10", "Accept"=>"*/*", "Accept-Encoding"=>"gzip, deflate"

=> 6

超时 = read_timeout + open_timeout

open_timeout:是连接建立失败后请求被拒绝的时间

read_timeout:您愿意等待从服务器接收一些数据的时间

  RestClient::Request.execute(url: "http://httpbin.org/delay/#{delay * 10}",
                            method: 'GET',
                            timeout: 1)

总结一下,

它是 Net::HTTP 库中需要的功能。 Ruby 2.5 应该有一个参数来覆盖该功能。

更多信息来自 https://engineering.wework.com/ruby-users-be-wary-of-net-http-f284747288b2

谢谢大家的回复!