释放elasticsearch连接

时间:2014-11-30 12:34:39

标签: elasticsearch singleton

我正在部署一个webapp,它在内部查询elasticsearch。我只创建一个连接,我想在webapp关闭时关闭它。我使用单例模式创建ES客户端以及如何销毁/关闭ES客户端?当应用程序关闭时,客户端是否会关闭,或者我必须指定它/我应该在哪里关闭连接的代码?

这是我的代码:

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;
    }
}

1 个答案:

答案 0 :(得分:0)

sample java code确实显示对client.close();

的调用

当您的应用关闭时调用此方法,或look into hooks强制它运行。