-
maven导入依赖
<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp --> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>3.10.0</version> </dependency>
-
构建OkHttpClient
new OkHttpClient.Builder()
//是否自动重连
.retryOnConnectionFailure(true)
// .addInterceptor(CustomerOkHttpRetryInterceptor.defaultInstance())
.connectionPool(new ConnectionPool())
//设置连接超时
.connectTimeout(3000, TimeUnit.MILLISECONDS)
//设置读超时
.readTimeout(10000, TimeUnit.MILLISECONDS)
.build();
- 拦截器处理实现
/**
* OkHttp重试拦截器实现
* <p>
* link: https://blog.csdn.net/a491857321/article/details/78144664
*
* @author wangqimeng
* @date 2019/9/19 11:23
*/
@Slf4j
public class CustomerOkHttpRetryInterceptor implements Interceptor {
/**
* 最大重试次数
*/
private int executionCount;
/**
* 重试的间隔
*/
private long retryInterval;
public CustomerOkHttpRetryInterceptor(Builder builder) {
this.executionCount = builder.executionCount;
this.retryInterval = builder.retryInterval;
}
/**
* 获取默认示例配置
*/
public static CustomerOkHttpRetryInterceptor defaultInstance() {
return new CustomerOkHttpRetryInterceptor.Builder()
.executionCount(3)
.retryInterval(1000)
.build();
}
/**
* 请求拦截处理
*
* @param chain 请求链
* @return Response
* @throws IOException io异常
*/
@Override
public Response intercept(Chain chain) throws IOException {
//当前重试次数
int retryNum = 0;
//获取request对象
Request request = chain.request();
//初次请求
Response response = firstRequest(chain, request);
while ((response == null || !response.isSuccessful())) {
log.info("intercept Request is not successful - {}", retryNum);
final long nextInterval = getRetryInterval();
try {
log.info("Wait for {}", nextInterval);
TimeUnit.MILLISECONDS.sleep(nextInterval);
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
throw new InterruptedIOException();
}
retryNum++;
// retry the request
try {
return chain.proceed(request);
} catch (IOException e) {
log.error("请求过程中异常", e);
//如果达到最大重试次数 抛出异常信息
if (executionCount == retryNum) {
throw e;
}
response = null;
}
}
return response;
}
/**
* 初次请求
*/
private Response firstRequest(Chain chain, Request request) {
try {
return chain.proceed(request);
} catch (Exception e) {
log.error("请求过程中异常", e);
}
return null;
}
/**
* retry间隔时间
*/
public long getRetryInterval() {
return this.retryInterval;
}
public static final class Builder {
private int executionCount;
private long retryInterval;
public Builder() {
executionCount = 3;
retryInterval = 1000;
}
public CustomerOkHttpRetryInterceptor.Builder executionCount(int executionCount) {
this.executionCount = executionCount;
return this;
}
public CustomerOkHttpRetryInterceptor.Builder retryInterval(long retryInterval) {
this.retryInterval = retryInterval;
return this;
}
public CustomerOkHttpRetryInterceptor build() {
return new CustomerOkHttpRetryInterceptor(this);
}
}
}