因为此问题不是必现,故不太好定位排查,根据关键异常信息:EOF
通常指输入流达到末尾,没法继续从数据流中读取; 怀疑多是因为双方(client<->server) 创建的链接,某一方主动close了,为了验证以上猜测,笔者查阅了相关资料,以及作了一些简单的代码实验
java
截图连接git
根据@edallagnol 描述,当两次请求时间间隔超过server端配置的keep-alive timeout
,server端会主动关闭当前链接,Okhttp
链接池ConnectionPool
默认超时时间是5min,也就是说优先复用链接池中的链接,然而server已经主动close,致使输入流中断,进而抛出EOF
异常。其中keep-alive
:两次请求之间的最大间隔时间 ,超过这个间隔 服务器会主动关闭这个链接, 主要是为了不从新创建链接,已节约服务器资源github
问题复现:c#
// Note: 须要保证server端配置的keep-alive timeout 为60s
OkHttpClient client = new OkHttpClient.Builder()
.retryOnConnectionFailure(false)
.build();
try {
for (int i = 0; i != 10; i++) {
Response response = client.newCall(new Request.Builder()
.url("http://192.168.50.210:7080/common/version/demo")
.get()
.build()).execute();
try {
System.out.println(response.body().string());
} finally {
response.close();
}
Thread.sleep(61000);
}
} catch (Exception e) {
e.printStackTrace();
}
复制代码
在进行常规的breakpoint
以后, 须要重点关注 RetryAndFollowUpInterceptor.java
Http1Codec.java
RealBufferedSource.java
这几个类服务器
RetryAndFollowUpInterceptor.java
public class RetryAndFollowUpInterceptor implements Interceptor {
//....
@Override public Response intercept(Chain chain) throws IOException {
//....
while(true) {
try {
response = realChain.proceed(request, streamAllocation, null, null);
releaseConnection = false;
} catch (IOException) {
// An attempt to communicate with a server failed. The request may have been sent.
boolean requestSendStarted = !(e instanceof ConnectionShutdownException);
// 此处很是重要,若不容许恢复,直接将异常向上抛出(调用方接收),反之 循环继续执行realChain.proceed()方法
if (!recover(e, streamAllocation, requestSendStarted, request)) throw e;
releaseConnection = false;
continue;
}
}
private boolean recover(IOException e, StreamAllocation streamAllocation, boolean requestSendStarted, Request userRequest) {
// ....
/ The application layer has forbidden retries.
// 若客户端配置 retryOnConnectionFailure 为false 则代表不容许重试,直接将异常抛给调用方
if (!client.retryOnConnectionFailure()) return false;
}
//....
}
复制代码
当执行realChain.proceed()
,将事件继续分发给各个拦截器,最终执行到 Http1Codec#readResponseHeaders
方法app
Http1Codec.java
public class Http1Codec implements HttpCodec {
//...
@Override public Response.Builder readResponseHeaders(boolean expectContinue) throws IOException {
try{
StatusLine statusLine = StatusLine.parse(readHeaderLine());
//后续代码根据statusLine 构造Response
} catch(EOFException e) {
// 原来异常信息就是从这里抛出来的,接下来须要重点关注下readHeaderLine方法
// Provide more context if the server ends the stream before sending a response.
IOException exception = new IOException("unexpected end of stream on " + streamAllocation);
exception.initCause(e);
}
}
private String readHeaderLine() throws IOException {
// 继续查看RealBufferedSource#readUtf8LineStrict方法
String line = source.readUtf8LineStrict(headerLimit);
headerLimit -= line.length();
return line;
}
//...
}
复制代码
Http1Codec
用于Encode Http Request 以及 解析 Http Response的,上述代码用于获取头信息相关参数ide
RealBufferedSource.java
final class RealBufferedSource implements BufferedSource {
//...
// 因为server端已经closed,故buffer == null 将EOF异常向上抛出
@Override public String readUtf8LineStrict(long limit) throws IOException {
if (limit < 0) throw new IllegalArgumentException("limit < 0: " + limit);
long scanLength = limit == Long.MAX_VALUE ? Long.MAX_VALUE : limit + 1;
long newline = indexOf((byte) '\n', 0, scanLength);
if (newline != -1) return buffer.readUtf8Line(newline);
if (scanLength < Long.MAX_VALUE
&& request(scanLength) && buffer.getByte(scanLength - 1) == '\r'
&& request(scanLength + 1) && buffer.getByte(scanLength) == '\n') {
return buffer.readUtf8Line(scanLength); // The line was 'limit' UTF-8 bytes followed by \r\n.
}
Buffer data = new Buffer();
buffer.copyTo(data, 0, Math.min(32, buffer.size()));
throw new EOFException("\\n not found: limit=" + Math.min(buffer.size(), limit)
+ " content=" + data.readByteString().hex() + '…');
}
//...
}
复制代码
用一张图总结:源码分析
能够看出 Okhttp 处理拦截器这块,用到了责任链模式ui
根据上述分析,在建立OkHttpClient
实例时,只须要将retryOnConnectionFailure
设置为true ,在抛出EOF
异常时,让其能够继续去执行realChain.proceed
方法便可google