ruby 中restclient怎麼設定逾時時間和捕獲逾時異常

來源:互聯網
上載者:User

標籤:

先吐槽一下百度,就是個坑,翻遍了百度都沒翻到答案,還好Google給力。


有兩個方法,第一:繞過restclient直接使用原生方法:

RestClient::Request.execute(:method => :post, :url => @url, :timeout => 90000000)

這樣做的好處是不用重寫restclient整個模組,可以直接使用,但我比較喜歡第二種方法,那就是重寫restclient這個模組,代碼如下:

require ‘net/http‘

require ‘openssl‘

require ‘stringio‘

require ‘uri‘

require ‘zlib‘

require ‘restclient‘


Timeout_vaule = 30

OpenTimeout_vaule = 30


module RestClient2

  # include RestClient


  def self.get(url, headers={}, &block)

    RestClient::Request.execute(:method => :get, :url => url, :headers => headers, :timeout =>Timeout_vaule,:open_timeout =>OpenTimeout_vaule, &block)

  end


  def self.post(url, payload, headers={}, &block)

    RestClient::Request.execute(:method => :post, :url => url, :payload => payload, :headers => headers,:timeout =>Timeout_vaule,:open_timeout =>OpenTimeout_vaule, &block)

  end


  def self.patch(url, payload, headers={}, &block)

    RestClient::Request.execute(:method => :patch, :url => url, :payload => payload, :headers => headers,:timeout =>Timeout_vaule,:open_timeout =>OpenTimeout_vaule, &block)

  end


  def self.put(url, payload, headers={}, &block)

    RestClient::Request.execute(:method => :put, :url => url, :payload => payload, :headers => headers,:timeout =>Timeout_vaule,:open_timeout =>OpenTimeout_vaule, &block)

  end


  def self.delete(url, headers={}, &block)

    RestClient::Request.execute(:method => :delete, :url => url, :headers => headers,:timeout =>Timeout_vaule,:open_timeout =>OpenTimeout_vaule, &block)

  end


  def self.head(url, headers={}, &block)

    RestClient::Request.execute(:method => :head, :url => url, :headers => headers,:timeout =>Timeout_vaule,:open_timeout =>OpenTimeout_vaule, &block)

  end


  def self.options(url, headers={}, &block)

    RestClient::Request.execute(:method => :options, :url => url, :headers => headers,:timeout =>Timeout_vaule,:open_timeout =>OpenTimeout_vaule, &block)

  end


end

這樣就可以直接如同使用原生的restclient一樣去使用它,不過這樣的話ruby內建的timeout這個東西就不太好使了,雖然原本就沒好使過,所以需要捕獲的異常就變成了:RestClient::RequestTimeout


當然,這個異常可能有其他捕獲辦法,但這個定位好像挺準的,所以就用這個了

ruby 中restclient怎麼設定逾時時間和捕獲逾時異常

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.