package com.ruoyi.file.config.es;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticSearchConfig {

    @Bean
    public ElasticsearchClient elasticsearchClient() {
        // 创建低级REST客户端
        RestClientBuilder restClientBuilder = RestClient.builder(
                new HttpHost("8.134.76.66", 9200, "http"));

        // 配置请求超时设置
        restClientBuilder.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
            @Override
            public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) {
                return requestConfigBuilder
                        .setConnectTimeout(5000) // 连接超时时间 5秒
                        .setSocketTimeout(60000) // Socket超时时间 60秒
                        .setConnectionRequestTimeout(10000); // 获取连接超时时间 10秒
            }
        });

        // 配置HTTP客户端参数
        restClientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
            @Override
            public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                return httpClientBuilder
                        .setDefaultIOReactorConfig(IOReactorConfig.custom()
                                .setIoThreadCount(1) // IO线程数
                                .build());
            }
        });

        RestClient restClient = restClientBuilder.build();

        // 创建传输层
        ElasticsearchTransport transport = new RestClientTransport(
                restClient,
                new JacksonJsonpMapper());

        // 创建Elasticsearch客户端
        return new ElasticsearchClient(transport);
    }
}
