package com.example.repurchase.configuration;

import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.http.HttpHost;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author 黄树文
 * @date 2020/4/2 12:57
 */
public class EsClientPoolFactory implements PooledObjectFactory<RestHighLevelClient> {

    private Logger log = LoggerFactory.getLogger(EsClientPoolFactory.class);

    @Override
    public PooledObject<RestHighLevelClient> makeObject() throws Exception {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        //        credentialsProvider.setCredentials(AuthScope.ANY,
        //                new UsernamePasswordCredentials("elastic", "360lj2019"));  //es账号密码
        //                new UsernamePasswordCredentials("elastic", "elastic"));  //es账号密码
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("192.168.50.32", 9200),
                        new HttpHost("192.168.50.39", 9200),
                        new HttpHost("192.168.50.41", 9200),
                        new HttpHost("192.168.50.41", 9201)
                ).setHttpClientConfigCallback(httpClientBuilder -> {
                    httpClientBuilder.disableAuthCaching();
                    return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                })/*.setMaxRetryTimeoutMillis(2000)*/
        );
        return new DefaultPooledObject<>(client);
    }

    @Override
    public void destroyObject(PooledObject<RestHighLevelClient> pooledObject) throws Exception {

        log.info("destroyObject");
        RestHighLevelClient highLevelClient = pooledObject.getObject();
        highLevelClient.close();
    }

    @Override
    public boolean validateObject(PooledObject<RestHighLevelClient> pooledObject) {
        return false;
    }

    @Override
    public void activateObject(PooledObject<RestHighLevelClient> pooledObject) throws Exception {
        log.info("activateObject");
    }

    @Override
    public void passivateObject(PooledObject<RestHighLevelClient> pooledObject) throws Exception {
        log.info("passivateObject");
    }
}
