简体   繁体   English

何时在Elasticsearch中关闭TransportClient?

[英]When do I close TransportClient in Elasticsearch?

I would like to know what is the good practice when opening and closing java elasticsearch client. 我想知道打开和关闭java elasticsearch客户端时的良好做法是什么。 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() . 因此基本上可以告诉您何时应调用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. 结束服务器或应用程序后,只需关闭客户端即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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