Java相关
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java相关相关的知识,希望对你有一定的参考价值。
- 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.br/>*/
@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相关的主要内容,如果未能解决你的问题,请参考以下文章