2009-07-29 17 views
6

XMLをいくつかのWebサービスに投稿する小さなアプリケーションを開発しています。 これは、Net :: HTTP :: Post :: Postを使用して行われます。ただし、サービスプロバイダは再接続を使用することを推奨します。Rubyネットを使った再接続戦略の実装

ような何か: 第一の要求が失敗した - > 第二の要求が失敗した2秒後にもう一度やり直してください - > 第三の要求が失敗した5秒後に再試行してください - > 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)} 

ご協力いただきありがとうございます。

マット

答えて

15

Rubyの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 
+0

エクセレントそれで から変換コードです。ありがとう! – Matt

+0

Avdi、これをテストするには良い方法はありますか? (rspecまたはanyを使用) – Mike

+0

ありがとうございました。 Btwでは、残念ながら 'SomeException'は' StandardError'である必要があります。cf:http://stackoverflow.com/questions/5370697/what-s-the-best-way-to-handle-exceptions-from-nethttp。それは非過渡的な、実際のエラーであれば、偉大ではありませんが、少なくともそれはラインにスコープされ、飲み込まれません。 – chesterbr

2

私は再試行のために宝石retryableを使用します。

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 

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

先端の素敵な宝石thx – daniel

+0

彼らは等しくありません:最初に遅延が3つのタイをしている0,3,5,10;秒は1秒遅れで10回の試行をしています。 – hlcs

関連する問題