Implementing a Reconnect Strategy Using Ruby Net

I am developing a small application that sends XML to some web service. This is done using Net :: HTTP :: Post :: Post. However, the service provider recommends using reconnection.

Something like: 1st request does not work β†’ try again after 2 seconds 2nd request does not work β†’ try again after 5 seconds Third request does not work β†’ try again after 10 seconds ...

What would be a good approach to this? Just run the next piece of code in a loop, catch the exception and fire it again after a while? Or is there any other smart way to do this? Perhaps there are some built-in features in the Net package that I don’t know about?

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)} 

Thank you very much, always appreciate your support.

Matt

+6
ruby webservice-client
source share
2 answers

This is one of the rare times that Ruby retry in handy. Something like that:

 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 
+15
source share

I am using gem retryable to retry. With it, the code is converted from:

 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 

To:

 retryable( :tries => 10, :on => [SomeException] ) do response = Net::HTTP.start(url.host, url.port) {|http| http.request(request)} end 
+2
source share

All Articles