简体   繁体   中英

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 !

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() .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM