Created
May 31, 2019 18:11
-
-
Save nandosola/ae82e35c8ded1f41600d47148d236f7f to your computer and use it in GitHub Desktop.
Ruby Net::HTTP wrapper with retries in case of exceptions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'net/http' | |
module Utils | |
class Backoff | |
RETR = 5 | |
def initialize(&blk) | |
@retries = RETR | |
@cmd = blk | |
end | |
def run! | |
begin | |
@cmd.call | |
rescue StandardError => ex | |
if @retries > 0 | |
puts "Caught #{ex.class}: #{ex.message} - Retrying..." | |
backoff! | |
@retries -= 1 | |
retry | |
else | |
puts "ERROR: Not responding after #{RETR} retries! Giving up!" | |
exit | |
end | |
end | |
end | |
private | |
def backoff! | |
nap = (2**@retries - 1) / 2 | |
puts "sleeping for #{nap} seconds" | |
sleep nap | |
end | |
end | |
module SafeNetHTTP | |
def self.start(uri, opts, &blk) | |
(Backoff.new do | |
Net::HTTP.start(uri.host, uri.port, opts){ |handler| yield handler } | |
end).run! | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'net/http' | |
require 'uri' | |
require 'rufus-scheduler' | |
require_relative "safe_net_http" | |
include Utils | |
scheduler = Rufus::Scheduler.new | |
scheduler.in '3s' do | |
uri = URI.parse("http://google.com/") | |
resp = SafeNetHTTP.start(uri, use_ssl: false) do |http| | |
http.request(Net::HTTP::Get.new(uri.path)) | |
end | |
puts "got #{resp.code}" | |
## TODO: retry in case of resp.code 4xx, 5xx | |
end | |
scheduler.join |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment