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<InetSocketTransportAddress> transportAddress = new ArrayList<InetSocketTransportAddress>();

    private static Map<String, Client> clientMap = new ConcurrentHashMap<String, Client>();

    private static Map<String, Integer> 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<InetSocketTransportAddress> getAllAddress(Map<String, Integer> ips) {
        List<InetSocketTransportAddress> addressList = new ArrayList<InetSocketTransportAddress>();
        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<InetSocketTransportAddress> transportAddress) {
        Client client = new TransportClient(setting)
                .addTransportAddresses(transportAddress
                        .toArray(new InetSocketTransportAddress[transportAddress
                                .size()]));
        clientMap.put(setting.get("cluster.name"), client);
    }
}


你可能感兴趣的:(elasticsearch,client)