• -------------------------------------------------------------
  • ====================================

【Elasticsearch】Java Client连接池

elasticsearch dewbay 5年前 (2019-09-17) 2279次浏览 已收录 0个评论 扫描二维码

按照 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);
}
}


露水湾 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:【Elasticsearch】Java Client连接池
喜欢 (0)
[]
分享 (0)
关于作者:
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址