EsClientPool.java
1.85 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
51
52
53
54
55
56
57
58
package com.cjs.cms.util.elasticsearch;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
public class EsClientPool {
private GenericObjectPool<TransportClient> pool;
private GenericObjectPoolConfig config;
private Settings settings;
private TransportAddress[] transportAddress;
public EsClientPool(Settings settings, TransportAddress... transportAddress) {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(50);
config.setMaxIdle(1000 * 60 * 10);
config.setMaxWaitMillis(1000 * 60 * 10);
this.config = config;
this.settings = settings;
this.transportAddress = transportAddress;
}
public EsClientPool(GenericObjectPoolConfig config, Settings settings,
TransportAddress... transportAddress) {
this.config = config;
this.settings = settings;
this.transportAddress = transportAddress;
}
public void initPool() {
pool = new GenericObjectPool<TransportClient>(
new EsClientFactory(settings, transportAddress), config);
}
public TransportClient getResource() {
try {
return pool.borrowObject();
} catch (Exception e) {
throw new RuntimeException("获取ElasticSearch连接失败", e);
}
}
/**返还资源*/
public void returnResource(TransportClient resource) {
if (resource != null) {
pool.returnObject(resource);
}
}
/**销毁连接池*/
public void destroy() {
pool.close();
}
}