Java相關問題整理

Mr.YF發表於2018-12-29

1. OkHttpClient呼叫出現大量CLOSE_WAIT。

問題定位:

  凡是系統中出現大量的CLOSE_WAIT,說明你的程式碼寫的有問題,即:沒有關閉連線。

在OkHttpClient中,預設時 HTTP頭欄位 Connection 設定值為keep-alive,這樣會導致服務端斷開連線時,客戶端不能及時的斷開連線,從而出現大量的CLOSE_WAIT。

問題修改:

  把HTTP頭欄位 Connection 設定值為close

 

如下是一段短連線http呼叫程式碼。

package com.xman.httpclient;

import okhttp3.*;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * Created by wangyaofu on 2018/4/25.
 */
@Service
public class HttpServiceImpl {

    public final static int CONNECT_TIMEOUT =10000;
    public final static int READ_TIMEOUT=10000;
    public final static int WRITE_TIMEOUT=10000;

    public String httpGet(String url, String userAgent) {
            final Request request = new Request.Builder()
                    .url(url).header("User-Agent", userAgent).header("Connection", "close")
                    .build();
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .readTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS)
                    .writeTimeout(WRITE_TIMEOUT, TimeUnit.MILLISECONDS)
                    .connectTimeout(CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
                    .build();
        Response response;
        try {
            response = okHttpClient.newCall(request).execute();
            return response.body().string();
        } catch (Exception e) {
            //logger.error("httpGet err=" + e.getMessage());
        }
        return null;
    }

    public String httpPost(String url, String body) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), body);
        //建立一個請求物件
        Request request = new Request.Builder()
                .url(url).header("Connection", "close")
                .post(requestBody)
                .build();
        //傳送請求獲取響應
        try {
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .readTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS)
                    .writeTimeout(WRITE_TIMEOUT, TimeUnit.MILLISECONDS)
                    .connectTimeout(CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
                    .build();
            Response response=okHttpClient.newCall(request).execute();
            if (response != null && response.body() != null) {
                return response.body().string();
            }
        } catch (Exception e) {
            //logger.error("httpPost err=" + e.getMessage());
        }
        return null;
    }
}

  

相關文章