標籤:
先吐槽一下百度,就是個坑,翻遍了百度都沒翻到答案,還好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怎麼設定逾時時間和捕獲逾時異常