EsUtil.java 1.79 KB
package com.cjs.cms.util.elasticsearch;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;

public final class EsUtil {

    private static EsClientPool pool;

    public synchronized static EsClientPool getPool() {
        if (pool == null) {
            Settings.Builder builder = Settings.builder();
            //builder.put("cluster.name", "myClusterName");
            //builder.put("client.transport.sniff", true);
            //ping节点的超时时间,默认5s
            //builder.put("client.transport.ping_timeout", 5);
            //How often to sample / ping the nodes listed and connected. Defaults to 5s.
            //builder.put("client.transport.nodes_sampler_interval", 5);

            List<TransportAddress> adds = new ArrayList<TransportAddress>();
            try {
                adds.add(
                    new InetSocketTransportAddress(InetAddress.getByName("192.168.10.186"), 9300));
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            pool = new EsClientPool(builder.build(),
                adds.toArray(new TransportAddress[adds.size()]));
        }
        return pool;
    }

    public <T> T execute(EsCallback<T> callback) throws RuntimeException {
        TransportClient client = pool.getResource();
        try {
            return callback.doInClient(client);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            pool.returnResource(client);
        }
    }
}