gpt4 book ai didi

elasticsearch - elasticsearch-创建TransportClient单例实例

转载 作者:行者123 更新时间:2023-12-03 02:07:59 25 4
gpt4 key购买 nike

我正在尝试使用客户端的单例实例来创建多个索引。下面是相同的代码。但是每次我获取实例为null并创建一个新实例时。请让我知道我在做什么错

单例实例:

public class ESClientSingleton {

public static Client instance ;

private ESClientSingleton()
{}

public static Client getInstance()
{
if (instance == null)
{
System.out.println("the instance is null...");
ImmutableSettings.Builder settings = ImmutableSettings.settingsBuilder();
settings.put("node.client", true);
settings.put("node.data", false);
settings.put("node.name", "node-client");
settings.put("cluster.name", "elasticsearch");
settings.build();
instance = new TransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress("10.203.251.142", 9300));
//instance = client;
System.out.println("return the client");
return instance;
}
return instance;
}
}

调用方法:
public static IndexResponse insertESDocument(String nodeName, String json) throws MasterNotDiscoveredException, SocketException
{
Client client = ESClientSingleton.getInstance();
logger.debug("calling the es client");
logger.debug("the json received as == "+json);
IndexResponse response = client.prepareIndex("aricloud-nodes","node-entry",nodeName )
.setSource(json)
.execute()
.actionGet();
logger.debug("the document is successfully indexed...");
System.out.println("the document is indexed...");
//client.close();
return response;
}

最佳答案

为了实现Singleton模式,请使用枚举代替类。
枚举具有许多内置优势,可帮助我们简化单例实现。
有关更多信息,请引用joshua bloch的Effective Java。

关于elasticsearch - elasticsearch-创建TransportClient单例实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22956847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com