
package com.dgtis.data.config;


import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.message.BasicHeader;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


/**
 * @author koucx
 * @version 1.0
 * @descption: TODO
 * @company 神州数码通用软件（洛阳）有限公司
 * @copyright (c) 2019 LuoYang DGT Co'Ltd Inc. All rights reserved.
 * @date 2021-01-21
 * @since JDK1.8
 */

@Configuration
public class ElasticSearchConfig {

    @Value("${elasticsearch.hostlist}")
    private String hostlist;

    @Value("${elasticsearch.port}")
    private int esPort;

    @Value("${elasticsearch.cluster.name}")
    private String esName;

    /**
     * 超时时间设为5分钟
     */
    private static final int TIME_OUT = 5 * 60 * 1000;


    @Bean
    public RestClient esClient() {
        /*RestClient restClient = null;
        try {
            restClient = RestClient.builder(httpHost()).setMaxRetryTimeoutMillis(TIME_OUT)
                    .setHttpClientConfigCallback(httpClientBuilder -> {
                        RequestConfig.Builder requestConfigBuilder = RequestConfig.custom()
                                //超时时间5分钟
                                .setConnectTimeout(TIME_OUT)
                                //这就是Socket超时时间设置
                                .setSocketTimeout(TIME_OUT)
                                .setConnectionRequestTimeout(DEFAULT_CONNECTION_REQUEST_TIMEOUT_MILLIS);
                        httpClientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());
                        return httpClientBuilder;
                    })
                    .build();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return restClient;*/

        //配置可选参数
        RestClientBuilder builder = RestClient.builder(
                httpHost());
        Header[] defaultHeaders = new Header[]{new BasicHeader("header", "value")};
        //设置每个请求需要发送的默认headers，这样就不用在每个请求中指定它们。
        builder.setDefaultHeaders(defaultHeaders);
        // 设置应该授予的超时时间，以防对相同的请求进行多次尝试。默认值是30秒，与默认socket超时时间相同。
        // 如果自定义socket超时时间，则应相应地调整最大重试超时时间。
//        builder.set.setMaxRetryTimeoutMillis(10000);
        builder.setFailureListener(new RestClient.FailureListener() {
            public void onFailure(HttpHost host) {
                //设置一个监听程序，每次节点发生故障时都会收到通知，这样就可以采取相应的措施。
                //Used internally when sniffing on failure is enabled.(这句话没搞懂啥意思)
            }
        });
        builder.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
            @Override
            public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) {
                //设置允许修改默认请求配置的回调
                // （例如，请求超时，身份验证或org.apache.http.client.config.RequestConfig.Builder允许设置的任何内容）
//                return requestConfigBuilder.setSocketTimeout(TIME_OUT);
                return requestConfigBuilder
                        .setConnectTimeout(TIME_OUT)
                        .setSocketTimeout(TIME_OUT);
            }
        });
        /*builder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
            @Override
            public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                //设置允许修改http客户端配置的回调
                // （例如，通过SSL的加密通信，或者org.apache.http.impl.nio.client.HttpAsyncClientBuilder允许设置的任何内容）
                final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("cluster", null));
                return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }
        });*/
        return builder.build();
    }

    public HttpHost[] httpHost(){
        //解析hostlist配置信息
        String[] split = hostlist.split(",");
        //创建HttpHost数组，其中存放es主机和端口的配置信息
        HttpHost[] httpHostArray = new HttpHost[split.length];
        for(int i=0;i<split.length;i++){
            String item = split[i];
            httpHostArray[i] = new HttpHost(item.split(":")[0], Integer.parseInt(item.split(":")[1]), "http");
        }
        return httpHostArray;
    }
}

