使用Retrofit 2重试请求

发布时间 2023-03-22 21:16:46作者: 青竹玉简
package vip.mafengwo.retrofit.call;

import lombok.extern.slf4j.Slf4j;
import retrofit2.Call;
import retrofit2.Callback;

/**
* author: AlanMa
* description:
* create: 2023-03-22 17:16
*/
@Slf4j
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.error(TAG, t.getLocalizedMessage());
if (retryCount++ < TOTAL_RETRIES) {
log.info(TAG, "Retrying... (" + retryCount + " out of " + TOTAL_RETRIES + ")");
retry(call);
}
}

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