Reputation: 3805
I would like to know what is the good practice when opening and closing java elasticsearch client. Do I open and close it between each request ? Or can I use a single instance of client for all requests ?
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();
}
Thank you !
Upvotes: 3
Views: 3251
Reputation: 53849
You should use a single client for all your requests.
Opening a connection is a costly operation and you do not want to open and close one every time you issue a request.
Simply close the client when you end your server or application.
Upvotes: 3
Reputation: 2255
I think you don't have to close transport client after each request. It will be a too much of an overhead.
See the docs 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();
There you can see the comment lines "on startup" and "on shutdown". So basically that tells you when you should call client.close()
.
Upvotes: 5