ElasticSearch java api -单例模式

//单例模式
private static Settings getSettingInstance(){
if(settings==null){
synchronized (Settings.class) {
if(settings==null){
settings = ImmutableSettings.settingsBuilder()
// client.transport.sniff=true
// 客户端嗅探整个集群的状态,把集群中其它机器的ip地址自动添加到客户端中,并且自动发现新加入集群的机器
.put("client.transport.sniff", true).put("client", true)// 仅作为客户端连接
.put("data", false).put("cluster.name", clustername)// 集群名称
.build();
}
}
}
return settings;
}
//单例模式
private static TransportClient client;
private static TransportClient getIstance() {
if (client == null) {
//同步代码块(对象未初始化时,使用同步代码块,保证多线程访问时对象在第一次创建后,不再重复被创建)
synchronized (TransportClient.class) {
if (client == null) {
client = new TransportClient(getSettingInstance()).addTransportAddress(new InetSocketTransportAddress(hostname, Integer.parseInt(port1)))// TCP
// 连接地址
.addTransportAddress(new InetSocketTransportAddress(hostname, Integer.parseInt(port2)));
}
}
}
return client;
}
/**
* 创建索引 写入elasticsearch
*
* @param jsonlist
* 要创建索引的jsonlist数据
*/
public static void createIndex(List<JSONObject> jsonlist) {
searchRequestBuilder = getIstance().prepareSearch(index);
try {
// 创建索引
for (int i = 0; i < jsonlist.size(); i++) {
IndexResponse indexResponse = client.prepareIndex(index, type, jsonlist.get(i).getString("id")).setSource(jsonlist.get(i).toString())
.execute().actionGet();
if (indexResponse.isCreated()) {
System.out.println("创建成功!");
} else {
System.out.println("创建失败!");
}
}
}
catch (Exception e) {
e.printStackTrace();
}

}

posted @ 2017-07-26 11:49  洞玄巅峰  阅读(1794)  评论(0编辑  收藏  举报