问题现象:
服务器CPU过高,重启后两台服务器只能顶一个小时,CPU就过高,访问不了了
错误日志:
02-Mar-2020 10:46:17.749 SEVERE [http-nio-8080-Acceptor-0] org.apache.tomcat.util.net.NioEndpoint$Acceptor.run Socket accept failed
java.io.IOException: Too many open files
at sun.nio.ch.ServerSocketChannelImpl.accept0(Native Method)
at sun.nio.ch.ServerSocketChannelImpl.accept(ServerSocketChannelImpl.java:422)
at sun.nio.ch.ServerSocketChannelImpl.accept(ServerSocketChannelImpl.java:250)
at org.apache.tomcat.util.net.NioEndpoint$Acceptor.run(NioEndpoint.java:693)
at java.lang.Thread.run(Thread.java:745)
修改前代码:
static RestHighLevelClient client=null;
// 取得实例
public static synchronized RestHighLevelClient getClient() {
String address0 = PropertiesUtil.getValue("es_address0");
String address1 = PropertiesUtil.getValue("es_address1");
int port0 = Integer.valueOf(PropertiesUtil.getValue("es_port0"));
int port1 = Integer.valueOf(PropertiesUtil.getValue("es_port1"));
client = new RestHighLevelClient(
RestClient.builder(
new HttpHost(address0, port0, "http"),
new HttpHost(address1, port1, "http")));
return client;
}
错误原因:
client每次都创建连接,而且从不关闭
修改方案:
创建一个公用的client连接,每次查询时,先判断一下连接是否为空,如果为空,则新建一个,如果不为空,则公用之前的连接
修改后代码:
static RestHighLevelClient client=null;
// 取得实例
public static synchronized RestHighLevelClient getClient() {
if(client==null){
String address0 = PropertiesUtil.getValue("es_address0");
String address1 = PropertiesUtil.getValue("es_address1");
int port0 = Integer.valueOf(PropertiesUtil.getValue("es_port0"));
int port1 = Integer.valueOf(PropertiesUtil.getValue("es_port1"));
client = new RestHighLevelClient(
RestClient.builder(
new HttpHost(address0, port0, "http"),
new HttpHost(address1, port1, "http")));
}
return client;
}