記錄某次解決`Okhttp java.io.EOFException: \n not found: size=0 content= unexpected end

問題猜測

因爲此問題不是必現,故不太好定位排查,根據關鍵異常信息:EOF通常指輸入流達到末尾,沒法繼續從數據流中讀取; 懷疑多是因爲雙方(client<->server) 創建的鏈接,某一方主動close了,爲了驗證以上猜測,筆者查閱了相關資料,以及作了一些簡單的代碼實驗java

如何解決

Github Issue or google or stackoverflow?

截圖連接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

相關文章
相關標籤/搜索