使用Ruby Net实现重新连接策略

Mat*_*att 6 ruby reconnect webservice-client

我正在开发一个小型应用程序,它将XML发布到一些web服务.这是使用Net :: HTTP :: Post :: Post完成的.但是,服务提供商建议使用重新连接.

类似的事情:第一次请求失败 - > 2秒后再次尝试第二次请求失败 - > 5秒后再次尝试第3次请求失败 - > 10秒后再次尝试...

这样做有什么好办法?只需在循环中运行以下代码,捕获异常并在一段时间后再次运行它?或者还有其他聪明的方法吗?也许Net包甚至有一些我不知道的内置功能?

url = URI.parse("http://some.host")

request = Net::HTTP::Post.new(url.path)

request.body = xml

request.content_type = "text/xml"


#run this line in a loop??
response = Net::HTTP.start(url.host, url.port) {|http| http.request(request)}
Run Code Online (Sandbox Code Playgroud)

非常感谢,永远感谢您的支持.

马特

Avd*_*vdi 15

这是Ruby's retry派上用场的罕见场合之一.这些方面的东西:

retries = [3, 5, 10]
begin 
  response = Net::HTTP.start(url.host, url.port) {|http| http.request(request)}
rescue SomeException # I'm too lazy to look it up
  if delay = retries.shift # will be nil if the list is empty
    sleep delay
    retry # backs up to just after the "begin"
  else
    raise # with no args re-raises original error
  end
end
Run Code Online (Sandbox Code Playgroud)