Java相关问题整理
程序员文章站
2024-01-17 10:44:22
1. OkHttpClient调用出现大量CLOSE_WAIT。 问题定位: 凡是系统中出现大量的CLOSE_WAIT,说明你的代码写的有问题,即:没有关闭连接。 在OkHttpClient中,默认时 HTTP头字段 Connection 设置值为keep-alive,这样会导致服务端断开连接时,客 ......
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;
}
}
下一篇: Python爬虫用什么框架比较好?