java 使用Retrofit 2重试请求

13z8s7eq  于 2023-01-11  发布在  Java
关注(0)|答案(8)|浏览(374)

我怎样才能添加重试功能到Retrofit 2库发送的请求中。

service.listItems().enqueue(new Callback<List<Item>>() {
        @Override
        public void onResponse(Response<List<Item>> response) {
            ...
        }

        @Override
        public void onFailure(Throwable t) {
            ...
        }
    }).retryOnFailure(5 /* times */);
wpcxdonn

wpcxdonn1#

我终于做了这样的事,给大家看:

1

首先我创建了一个抽象类CallbackWithRetry

public abstract class CallbackWithRetry<T> implements Callback<T> {

    private static final int TOTAL_RETRIES = 3;
    private static final String TAG = CallbackWithRetry.class.getSimpleName();
    private final Call<T> call;
    private int retryCount = 0;

    public CallbackWithRetry(Call<T> call) {
        this.call = call;
    }

    @Override
    public void onFailure(Throwable t) {
        Log.e(TAG, t.getLocalizedMessage());
        if (retryCount++ < TOTAL_RETRIES) {
            Log.v(TAG, "Retrying... (" + retryCount + " out of " + TOTAL_RETRIES + ")");
            retry();
        }
    }

    private void retry() {
        call.clone().enqueue(this);
    }
}

使用这个类,我可以做类似这样的事情:

serviceCall.enqueue(new CallbackWithRetry<List<Album>>(serviceCall) {
    @Override
    public void onResponse(Response<List<Album>> response) {
        ...
    }
});

2

这并不完全令人满意,因为我必须传递相同的serviceCall两次。这可能会令人困惑,因为人们可能会认为第二个serviceCall(进入CallbackWithRetry的构造函数)应该或可能与第一个不同(我们在其上调用enqueue方法)
所以我实现了一个helper类CallUtils

public class CallUtils {

    public static <T> void enqueueWithRetry(Call<T> call, final Callback<T> callback) {
        call.enqueue(new CallbackWithRetry<T>(call) {
            @Override
            public void onResponse(Response<T> response) {
                callback.onResponse(response);
            }

            @Override
            public void onFailure(Throwable t) {
                super.onFailure(t);
                callback.onFailure(t);
            }
        });
    }

}

我可以这样使用它:

CallUtils.enqueueWithRetry(serviceCall, new Callback<List<Album>>() {
    @Override
    public void onResponse(Response<List<Album>> response) {
        ...
    }

    @Override
    public void onFailure(Throwable t) {
        // Let the underlying method do the job of retrying.
    }
});

这样,我必须将一个标准的Callback传递给enqueueWithRetry方法,它使我实现onFailure(尽管在前面的方法中我也可以实现它)
这就是我解决这个问题的方法。如果你能给我一个更好的设计建议,我将不胜感激。

iyfjxgzm

iyfjxgzm2#

我已经定制了Callback接口的实现,你可以用它来代替原来的回调。如果调用成功,onResponse()方法被调用。如果在设置的重复次数后重试调用失败,onFailedAfterRetry()方法被调用。

public abstract class BackoffCallback<T> implements Callback<T> {
private static final int RETRY_COUNT = 3;
/**
 * Base retry delay for exponential backoff, in Milliseconds
 */
private static final double RETRY_DELAY = 300;
private int retryCount = 0;

@Override
public void onFailure(final Call<T> call, Throwable t) {
    retryCount++;
    if (retryCount <= RETRY_COUNT) {
        int expDelay = (int) (RETRY_DELAY * Math.pow(2, Math.max(0, retryCount - 1)));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                retry(call);
            }
        }, expDelay);
    } else {
        onFailedAfterRetry(t);
    }
}

private void retry(Call<T> call) {
    call.clone().enqueue(this);
}

public abstract void onFailedAfterRetry(Throwable t);

}

https://gist.github.com/milechainsaw/811c1b583706da60417ed10d35d2808f

cwdobuhd

cwdobuhd3#

ashkan-sarlak答案工作得很好,我只是想让它保持最新状态。
retrofit 2.1

onFailure(Throwable t)

更改为

onFailure(Call<T> call, Throwable t)

现在就很简单了。像这样创建CallbackWithRetry.java

public abstract class CallbackWithRetry<T> implements Callback<T> {

    private static final int TOTAL_RETRIES = 3;
    private static final String TAG = CallbackWithRetry.class.getSimpleName();
    private int retryCount = 0;

    @Override
    public void onFailure(Call<T> call, Throwable t) {
        Log.e(TAG, t.getLocalizedMessage());
        if (retryCount++ < TOTAL_RETRIES) {
            Log.v(TAG, "Retrying... (" + retryCount + " out of " + TOTAL_RETRIES + ")");
            retry(call);
        }
    }

    private void retry(Call<T> call) {
        call.clone().enqueue(this);
    }
}

就这样!你可以这样简单地使用它

call.enqueue(new CallbackWithRetry<someResponseClass>() {

        @Override
        public void onResponse(@NonNull Call<someResponseClass> call, @NonNull retrofit2.Response<someResponseClass> response) {
            //do what you want
        }
        @Override
        public void onFailure(@NonNull Call<someResponseClass> call, @NonNull Throwable t) {
            super.onFailure(call,t);
            //do some thing to show ui you trying
            //or don't show! its optional
        }
    });
yxyvkwin

yxyvkwin5#

我做了一些与Ashkan Sarlak非常相似的事情,但是由于Retrofit 2.1将Call<T>传递到onFailure方法中,因此可以简化为一个CallbackWithRetry<T>抽象类。

public abstract class CallbackWithRetry<T> implements Callback<T> {


 private static final String TAG = "CallbackWithRetry";

  private int retryCount = 0;

  private final Logger logger;
  private final String requestName;
  private final int retryAttempts;

  protected CallbackWithRetry(@NonNull Logger logger, @NonNull String requestName, int retryAttempts) {
    this.logger = logger;
    this.requestName = requestName;
    this.retryAttempts = retryAttempts;
  }

  @Override
  public void onFailure(Call<T> call, Throwable t) {
    if (retryCount < retryAttempts) {
      logger.e(TAG, "Retrying ", requestName, "... (", retryCount, " out of ", retryAttempts, ")");
      retry(call);

      retryCount += 1;
    } else {
      logger.e(TAG, "Failed request ", requestName, " after ", retryAttempts, " attempts");
    }
  }

  private void retry(Call<T> call) {
    call.clone().enqueue(this);
  }
}
cld4siwp

cld4siwp6#

带改型2.5
现在可以通过java.util.concurrent.completableFuture进行异步同步调用,代码等待它的完成,这非常好。
下面是一个gist,其中包含一个有效的解决方案。

3df52oht

3df52oht7#

如果重试是可选的,则此问题的另一解决方案是:

public class CustomCallback<T> implements Callback<T> {
    @NonNull
    Callback<T> callback;

    private int retryCount = 0;
    private int maxRetry = 0;

    @EverythingIsNonNull
    public CustomCallback(Callback<T> callback) {
        this.callback = callback;
    }

    public CustomCallback<T> retryOnFailure(int nbRetry) {
        maxRetry = nbRetry;
        return this;
    }

    @EverythingIsNonNull
    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        callback.onResponse(call, response);
    }

    @EverythingIsNonNull
    @Override
    public void onFailure(Call<T> call, Throwable t) {
        if (maxRetry > retryCount) {
            retryCount++;
            call.clone().enqueue(this);
            return;
        }
        callback.onFailure(call, t);
    }
}

这样,您就可以选择是否重试:

//With retry
 myAPI.makeCall().enqueue(new CustomCallback<>(myCallback).retryOnFailure(3));
//Without
 myAPI.makeCall().enqueue(new CustomCallback<>(myCallback));
yi0zb3m4

yi0zb3m48#

我认为对于Android来说,我们不需要为此进行改造。我们可以利用工作管理器(它预定义了Android API)。我们可以使用“ListenableWorker.Result.SUCCESS”,“ListenableWorker.Result.RETRY”等来实现上述目标。

相关问题