問題定位:java
凡是系統中出現大量的CLOSE_WAIT,說明你的代碼寫的有問題,即:沒有關閉鏈接。spring
在OkHttpClient中,默認時 HTTP頭字段 Connection 設置值爲keep-alive,這樣會致使服務端斷開鏈接時,客戶端不能及時的斷開鏈接,從而出現大量的CLOSE_WAIT。json
問題修改:app
把HTTP頭字段 Connection 設置值爲closepost
以下是一段短鏈接http調用代碼。ui
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; } }