How to implement HttpRequestRetryHandler with exponential rollback?

I want to implement an HttpRequestRetryHandler for an HttpClient in case of a first request failure.

I also want to implement Exponential Shutdown for subsequent attempts. Mathematically, it can be implemented as

E (c) = 1/2 (2 power (c) -1)

enter image description here

but I have been struggling for a long time to implement it in code with HttpRequestRetryHandler.

+6
source share
3 answers

HttpRequestRetryHandler does not allow you to control the level; if you want to do something very specific, I would recommend implementing something like Handler , where you can send Runnables to start using delay, using, for example, Handler.postDelayed () with an increase in delay according to your formula.

Handler mHandler = new Handler(); int mDelay = INITIAL_DELAY; // try request mHandler.postDelayed(mDelay, new Runnable() { public void run() { // try your request here; if it fails, then repost: if (failed) { mDelay *= 2; // or as per your formula mHandler.postDelayed(mDelay, this); } else { // success! } } }); 
+3
source

Here is a nice structure with deferral algorithms - https://github.com/rholder/guava-retrying

+1
source

I use guava-retrying for a strategy to call an arbitrary function again.

I integrate it with the Guavaberry library that I wrote, and which contains several waiting strategies that make it easy to build a solid exponential delay in combination with a random interval (aka jitter): ExponentialJitterWaitStrategy

For example, to create an exponential delay of up to 15 seconds and with a jitter of 50% on the called:

 Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder() .retryIfResult(Predicates.isNull()) .withWaitStrategy(WaitStrategies.exponentialJitterWait(Duration.ofSeconds(15), 0.5D)) .build(); retryer.call(callable); 

The library is well tested and documented and can be easily integrated through Maven Central.

Hope this helps.

0
source

All Articles