2017-02-12 111 views
0

我想知道什么是打开和关闭java elasticsearch客户端时的良好做法。 我是否在每次请求之间打开和关闭它?或者我可以为所有请求使用单个客户端实例吗?什么时候关闭Elasticsearch中的TransportClient?

private Client client; 

@PostConstruct 
public void init() { 
    try { 
     client = new PreBuiltTransportClient(Settings.EMPTY) 
       .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port)); 
    } catch (UnknownHostException e) { 
     LOGGER.error("Unable to create ESClient : {}", e); 
    } 
} 

@PreDestroy 
public void destroy() { 
    client.close(); 
} 

谢谢!

回答

2

我想你不必在每次请求后关闭传输客户端。这将是一个过多的开销。请参阅文档here

// on startup 

TransportClient client = new PreBuiltTransportClient(Settings.EMPTY) 
     .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("host1"), 9300)) 
     .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("host2"), 9300)); 

// on shutdown 

client.close(); 

在那里你可以看到注释行“on startup”和“on shutdown”。所以基本上,这告诉你什么时候应该打电话给client.close()

1

您应该为您的所有请求使用单个客户端。

打开连接是一项代价高昂的操作,每次发出请求时都不想打开和关闭连接。

当您结束服务器或应用程序时,只需关闭客户端即可。

相关问题