EsClientPool.java 1.85 KB
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();
    }
}