connect reset问题
服务器发生connect reset原因不详说了,没有见过的可以看下connect reset原因
这个博客讲述的很正确,稍微补充下,有时改成短链接不一定能完全解决该问题,因为在http请求发送和返回响应肯定是需要时间的,在服务器高并发环境下很容易触发安全策略或者其他策略导致链接强制断开,因此需要在转化成短链接的同时增加重试才能根本解决问题。
这里使用okhttp4使用拦截器重试,这样能大概率解决所有问题
private static OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(0, TimeUnit.SECONDS)
.readTimeout(0, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.addInterceptor(myOkHttpRetryInterceptor)
.build();
其中myOkHttpRetryInterceptor可以仿照这个博客编写
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);
}
}
}