当前位置:
ElasticSearch 连接池工具类
机器助手 | 2025-07-13
86人浏览
package com.biemo.elasticsearch.util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
/**
* ElasticSearch 连接池工具类
*/
@Slf4j
@Component
public class ElasticSearchPoolUtil{
@Autowired
ElasticsearchClientPoolFactory esClientPoolFactory;
private static GenericObjectPool<RestHighLevelClient> clientPool;
private static GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
static {
poolConfig.setMaxIdle(200);
poolConfig.setMaxTotal(50);
poolConfig.setMinEvictableIdleTimeMillis(1000L*3L);
}
@PostConstruct
public void init() {
// 对象池配置类,不写也可以,采用默认配置
// 利用对象工厂类和配置类生成对象池
clientPool = new GenericObjectPool<>(esClientPoolFactory, poolConfig);
}
/**
* 获得对象
*
* @return
* @throws Exception
*/
public static RestHighLevelClient getClient() throws Exception {
// 从池中取一个对象
RestHighLevelClient client = clientPool.borrowObject();
return client;
}
/**
* 归还对象
*
* @param client
*/
public static void returnClient(RestHighLevelClient client) {
// 使用完毕之后,归还对象
clientPool.returnObject(client);
}
/**
* 销毁对象
*
* @param client
*/
public static void destroyClient(RestHighLevelClient client) {
try {
// 发生异常之后,销毁对象
clientPool.invalidateObject(client);
} catch (Exception e) {
log.error("ElasticSearchPoolUtil.destroyClient error:", e);
}
}
}
