何使用指数回退实现HttpRequestRetryHandler

何使用指数回退实现HttpRequestRetryHandler

本文介绍了如何使用指数回退实现HttpRequestRetryHandler?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望为HttpClient实现 HttpRequestRetryHandler ,以防请求第一次失败.

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次幂(c)-1)

但是我现在要花很多时间才能在代码中实现它带有HttpRequestRetryHandler.

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

推荐答案

HttpRequestRetryHandler不允许您进行这种级别的控制;如果您想做一些非常具体的事情,建议您实施处理程序,您可以在其中发布要延迟执行的Runnable,例如使用Handler.postDelayed()(根据您的公式,其延迟增加).

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

这篇关于如何使用指数回退实现HttpRequestRetryHandler?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 09:45