com.feingto.cloud.kit.http.OKHttpRetryIntercepter Maven / Gradle / Ivy
package com.feingto.cloud.kit.http;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
import java.io.InterruptedIOException;
/**
* OKHttp 响应失败重试
*
* @author longfei
*/
@Slf4j
public class OKHttpRetryIntercepter implements Interceptor {
/**
* 最大重试次数
*/
private final int maxAutoRetries;
/**
* 重试频率
*/
private final int retryInterval;
public OKHttpRetryIntercepter(int maxAutoRetries, int retryInterval) {
this.maxAutoRetries = maxAutoRetries;
this.retryInterval = retryInterval;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
int retryNum = 0;
while (!response.isSuccessful() && retryNum < maxAutoRetries) {
try {
Thread.sleep(retryInterval);
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
throw new InterruptedIOException();
}
retryNum++;
log.error("Request failed and retried {} times", retryNum);
response = chain.proceed(request);
}
return response;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy