码迷,mamicode.com
首页 > 其他好文 > 详细

ruby 中restclient怎么设定超时时间和捕获超时异常

时间:2015-11-11 16:51:46      阅读:285      评论:0      收藏:0      [点我收藏+]

标签:

先吐槽一下百度,就是个坑,翻遍了百度都没翻到答案,还好谷歌给力。


有两个方法,第一:绕过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怎么设定超时时间和捕获超时异常

标签:

原文地址:http://my.oschina.net/zxzllyj/blog/528925

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!