您的位置:首页 > 理论基础 > 计算机网络

OkHttp实现延时重试

2017-09-30 18:04 141 查看

场景分析

很多项目由于有callback,且失败重试和重定向需求,因此需要实现OkHttp失败重试

解决方案

package com.gomefinance.esign.httpretry;

import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.List;

/**
* User: Administrator
* Date: 2017/9/19
* Description:
*/

@Slf4j
public class MyOkHttpRetryInterceptor implements Interceptor {
public int executionCount;//最大重试次数
private long retryInterval;//重试的间隔
MyOkHttpRetryInterceptor(Builder builder) {
this.executionCount = builder.executionCount;
this.retryInterval = builder.retryInterval;
}

@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = doRequest(chain, request);
int retryNum = 0;
while ((response == null || !response.isSuccessful()) && retryNum <= executionCount) {
log.info("intercept Request is not successful - {}",retryNum);
final long nextInterval = getRetryInterval();
try {
log.info("Wait for {}",nextInterval);
Thread.sleep(nextInterval);
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
throw new InterruptedIOException();
}
retryNum++;
// retry the request
response = doRequest(chain, request);
}
return response;
}

private Response doRequest(Chain chain, Request request) {
Response response = null;
try {
response = chain.proceed(request);
} catch (Exception e) {
}
return response;
}

/**
* 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 MyOkHttpRetryInterceptor.Builder executionCount(int executionCount){
this.executionCount =executionCount;
return this;
}

public MyOkHttpRetryInterceptor.Builder retryInterval(long retryInterval){
this.retryInterval =retryInterval;
return this;
}
public MyOkHttpRetryInterceptor build() {
return new MyOkHttpRetryInterceptor(this);
}
}

}

实现方法

MyOkHttpRetryInterceptor myOkHttpRetryInterceptor = new MyOkHttpRetryInterceptor.Builder()
.executionCount(3)
.retryInterval(1000)
.build();
new OkHttpClient.Builder()
.retryOnConnectionFailure(true)
.addInterceptor(myOkHttpRetryInterceptor)
.connectionPool(new ConnectionPool())
.connectTimeout(3000, TimeUnit.MILLISECONDS)
.readTimeout(10000, TimeUnit.MILLISECONDS)
.build();

实现请求失败切换IP重试的方案
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息