Elasticsearch Java Client连接池

原创
2017/02/16 13:54
阅读数 2K

按照Elasticsearch API,在Java端使用是ES服务需要创建Java Client,但是每一次连接都实例化一个client,对系统的消耗很大,即使在使用完毕之后将client close掉,由于服务器不能及时回收socket资源,极端情况下会导致服务器达到最大连接数。

为了解决上述问题并提高client利用率,可以参考使用池化技术复用client。

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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/** * Created by tgg on 16-3-17. */
public class ClientHelper {

    private Settings setting;

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

    private Map<String, Integer> ips = new HashMap<String, Integer>(); // hostname port

    private String clusterName = "elasticsearch";

    private ClientHelper() {
        init();
        //TO-DO 添加你需要的client到helper
    }

    public static final ClientHelper getInstance() {
        return ClientHolder.INSTANCE;
    }

    private static class ClientHolder {
        private static final ClientHelper INSTANCE = new ClientHelper();
    }

    /** * 初始化默认的client */
    public void init() {
        ips.put("127.0.0.1", 9300);
        setting = ImmutableSettings
                .settingsBuilder()
                .put("client.transport.sniff",true)
                .put("cluster.name","elasticsearch").build();
        addClient(setting, getAllAddress(ips));
    }

    /** * 获得所有的地址端口 * * @return */
    public 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 Client getClient() {
        return getClient(clusterName);
    }

    public Client getClient(String clusterName) {
        return clientMap.get(clusterName);
    }

    public 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);
    }
}
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部