EsUtil.java
1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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);
}
}
}