1. OkHttpClient调用出现大量CLOSE_WAIT。
问题定位:
凡是系统中出现大量的CLOSE_WAIT,说明你的代码写的有问题,即:没有关闭连接。
在OkHttpClient中,默认时 HTTP头字段 Connection 设置值为keep-alive,这样会导致服务端断开连接时,客户端不能及时的断开连接,从而出现大量的CLOSE_WAIT。
问题修改:
把HTTP头字段 Connection 设置值为close
如下是一段短连接http调用代码。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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;
}欢迎工作一到五年的Java工程师朋友们加入Java群: 891219277
群内提供免费的Java架构学习资料(里面有高可用、高并发、高性能及分布式、Jvm性能调优、Spring源码,MyBatis,Netty,Redis,Kafka,Mysql,Zookeeper,Tomcat,Docker,Dubbo,Nginx等多个知识点的架构资料)合理利用自己每一分每一秒的时间来学习提升自己,不要再用"没有时间“来掩饰自己思想上的懒惰!趁年轻,使劲拼,给未来的自己一个交代!
网友评论