Prachi g
Prachi g

Reputation: 839

Releasing elasticsearch connection

I am deploying a webapp, which internally queries elasticsearch. I am creating only one connection, and I want to close it when the webapp shuts down. I am using singleton pattern for creating the ES client and how do I destroy/close ES client? When the application shuts down, will the client get closed or I have to specify it/ where should I have the code to close the connection?

This is my code:

public class ESClientManager {

    public static Client client = null;
    private static Settings settings = null;
    private static Object mutex = new Object();
    private static final String CONFIG_CLUSTER_NAME = "cluster.name";
    private static final String CLUSTER_NAME = "qatool_es";
    private static final String[] transportAddress = {
           "127.0.0.1"
    };

    private static final int transportPort = 9300;

    private ESClientManager() {
    }

    public static Client getClient() {
        if (client == null) {
            synchronized (mutex) {
                settings = ImmutableSettings.settingsBuilder()
                        .put(CONFIG_CLUSTER_NAME, CLUSTER_NAME).build();

                client = new TransportClient(settings);
                for (int i = 0; i < transportAddress.length - 1; i++) {
                    ((TransportClient) client).addTransportAddress(new InetSocketTransportAddress(transportAddress[i], transportPort));
                }
                logger.info("Elastic search client initialized");
            }
        }
        logger.info("Returning the existing client");
        return client;
    }
}

Upvotes: 1

Views: 407

Answers (1)

Alain Collins
Alain Collins

Reputation: 16362

The sample java code does show a call to client.close();

Call this when your app closes, or look into hooks to force it to be run.

Upvotes: 1

Related Questions