How to implement HttpRequestRetryHandler with Exponential Backoff?

江枫思渺然 提交于 2019-12-22 05:14:40

问题


I wish to implement a HttpRequestRetryHandler for a HttpClient in case the request fails first time.

I also wish to implement Exponential backoff for subsequent retries. Mathematically it can be implemented as

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

but I am struggling for quite some time now to implement it in the code with HttpRequestRetryHandler.


回答1:


HttpRequestRetryHandler doesn't allow you that level of control; if you want to do something very specific like that, I'd recommend implementing something like a Handler where you can post Runnables to be executed with a delay, using for example Handler.postDelayed() with increasing delays as per 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!
      }
   }
});



回答2:


Here is a good framework with backoff algorithms - https://github.com/rholder/guava-retrying




回答3:


I use guava-retrying for a strategy of retrying arbitrary function call.

I integrate it with a library Guavaberry that I wrote and that contains several waiting strategies that allow to easily build a solid exponential backoff combined with random interval (aka jitter) : ExponentialJitterWaitStrategy

For instance for building an exponential backoff capped to 15 seconds and with jitter of 50% on a callable:

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 via Maven Central.

I hope that can be of help.



来源:https://stackoverflow.com/questions/13809835/how-to-implement-httprequestretryhandler-with-exponential-backoff

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!