提交 e8a42723 编写于 作者: X Xin,Zhang 提交者: wu-sheng

fix httpclient not close (#122)

* fix httpclient issue
* @ascrutae As you pr too many commits, I will use `confirm squash and merge`.
上级 209791c2
...@@ -30,15 +30,11 @@ import org.apache.http.impl.client.HttpClients; ...@@ -30,15 +30,11 @@ import org.apache.http.impl.client.HttpClients;
public class CollectorClient implements Runnable { public class CollectorClient implements Runnable {
private static ILog logger = LogManager.getLogger(CollectorClient.class); private static ILog logger = LogManager.getLogger(CollectorClient.class);
private static long SLEEP_TIME_MILLIS = 500; private static long SLEEP_TIME_MILLIS = 500;
private CloseableHttpClient httpclient;
private String[] serverList; private String[] serverList;
private volatile int selectedServer = -1; private volatile int selectedServer = -1;
public CollectorClient() { public CollectorClient() {
serverList = Config.Collector.SERVERS.split(","); serverList = Config.Collector.SERVERS.split(",");
httpclient = HttpClients.custom()
.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())
.build();
Random r = new Random(); Random r = new Random();
if (serverList.length > 0) { if (serverList.length > 0) {
selectedServer = r.nextInt(serverList.length); selectedServer = r.nextInt(serverList.length);
...@@ -92,11 +88,13 @@ public class CollectorClient implements Runnable { ...@@ -92,11 +88,13 @@ public class CollectorClient implements Runnable {
.excludeFieldsWithoutExposeAnnotation() .excludeFieldsWithoutExposeAnnotation()
.create(); .create();
String messageJson = gson.toJson(message); String messageJson = gson.toJson(message);
CloseableHttpClient httpClient = HttpClients.custom()
.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())
.build();
try { try {
HttpPost httpPost = ready2Send(messageJson); HttpPost httpPost = ready2Send(messageJson);
if (httpPost != null) { if (httpPost != null) {
CloseableHttpResponse httpResponse = httpclient.execute(httpPost); CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
int statusCode = httpResponse.getStatusLine().getStatusCode(); int statusCode = httpResponse.getStatusLine().getStatusCode();
if (200 != statusCode) { if (200 != statusCode) {
findBackupServer(); findBackupServer();
...@@ -106,6 +104,8 @@ public class CollectorClient implements Runnable { ...@@ -106,6 +104,8 @@ public class CollectorClient implements Runnable {
} catch (IOException e) { } catch (IOException e) {
findBackupServer(); findBackupServer();
throw e; throw e;
}finally {
httpClient.close();
} }
} }
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册