Oreste Viron
Oreste Viron

Reputation: 3805

When do I close TransportClient in Elasticsearch?

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

Answers (2)

Jean Logeart
Jean Logeart

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

Rajind Ruparathna
Rajind Ruparathna

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

Related Questions