2004 发表于 2019-1-29 09:07:15

2:elasticsearch客户端创建

  根据elasticsearch的API,首先,要创建一个客户端实例Client,代码如下

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.netty.util.internal.ConcurrentHashMap;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;

/**
* client客户端帮助类
*
* @author tuoqiantu
* @date 2013-8-9 下午3:55:38
*
*/
public class ClientHelper {
    private static Settings setting;
    public static List transportAddress = new ArrayList();
    private static Map clientMap = new ConcurrentHashMap();
    private static Map ips=new HashMap();
    private static String clusterName = "node1";
    static {
      ips.put("192.168.1.100", 9300);
      ips.put("192.168.1.101", 9300);
      init();
    }
    /**
   * 初始化默认的client
   */
    public static void init() {
      setting = ImmutableSettings
                .settingsBuilder()
                .put("client.transport.sniff",true)
                .put("client",true)
                .put("data",false)
                .put("cluster.name","elasticsearch").build();
      transportAddress.addAll(getAllAddress(ips));
      Client client = new TransportClient(setting)
                .addTransportAddresses(transportAddress
                        .toArray(new InetSocketTransportAddress[transportAddress
                              .size()]));
      clientMap.put(clusterName, client);
    }
    /**
   * 获得所有的地址端口
   *
   * @return
   */
    public static List getAllAddress(Map ips) {
      List addressList = new ArrayList();
      for (String ip : ips.keySet()) {
            addressList.add(new InetSocketTransportAddress(ip, ips.get(ip)));
      }
      return addressList;
    }
    public static Client getClient() {
      return getClient(clusterName);
    }
    public static Client getClient(String clusterName) {
      return clientMap.get(clusterName);
    }
    public static void addClient(Settings setting,
            List transportAddress) {
      Client client = new TransportClient(setting)
                .addTransportAddresses(transportAddress
                        .toArray(new InetSocketTransportAddress[transportAddress
                              .size()]));
      clientMap.put(setting.get("cluster.name"), client);
    }
}  




页: [1]
查看完整版本: 2:elasticsearch客户端创建