ruby restclient超时无法正常工作,它在两倍的定义超时后引发异常

时间:2018-10-12 14:56:20

标签: ruby timeout rest-client

注意到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

2 个答案:

答案 0 :(得分:1)

作为总结,

在Net :: HTTP库上提供了所需的功能。 Ruby 2.5应该有一个参数可以覆盖该功能。

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

的更多信息

谢谢大家的答复!

答案 1 :(得分:0)

超时=读取超时+打开超时

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

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

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