释放elasticsearch连接

Posted

技术标签:

【中文标题】释放elasticsearch连接【英文标题】:Releasing elasticsearch connection 【发布时间】:2014-11-30 12:34:39 【问题描述】:

我正在部署一个 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】:

sample java code 确实显示了对 client.close(); 的调用

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

【讨论】:

以上是关于释放elasticsearch连接的主要内容,如果未能解决你的问题,请参考以下文章

解决golang使用elastic连接elasticsearch时自动转换连接地址

如何在 Kafka 连接器中正确连接 Elastic Operator 部署的 Elasticsearch?

Elastic Stack:Java客户端连接ElasticSearch

Elastic Stack:Java客户端连接ElasticSearch

释放elasticsearch连接

Elasticsearch:使用 Low Level Java 客户端来创建连接 - Elastic Stack 8.x