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.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;

@Configuration
public class ElasticSearchConfig {

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

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

    @Value("${elasticsearch.scheme:http}")
    private String scheme;

    @Value("${elasticsearch.connectTimeout:5000}")
    private int connectTimeout;

    @Value("${elasticsearch.socketTimeout:60000}")
    private int socketTimeout;

    @Value("${elasticsearch.connectionRequestTimeout:1000}")
    private int connectionRequestTimeout;

    @Value("${elasticsearch.maxConnTotal:100}")
    private int maxConnTotal;

    @Value("${elasticsearch.maxConnPerRoute:100}")
    private int maxConnPerRoute;

    @Bean
    public ElasticsearchClient elasticsearchClient() {
        RestClientBuilder builder = RestClient.builder(new HttpHost(host, port, scheme))
                .setRequestConfigCallback(requestConfigBuilder ->
                        requestConfigBuilder
                                .setConnectTimeout(connectTimeout)               // 连接超时
                                .setSocketTimeout(socketTimeout)                 // 读取超时
                                .setConnectionRequestTimeout(connectionRequestTimeout) // 从连接池获取连接的超时
                )
                .setHttpClientConfigCallback(httpClientBuilder ->
                        httpClientBuilder
                                .setMaxConnTotal(maxConnTotal)                   // 最大连接数
                                .setMaxConnPerRoute(maxConnPerRoute)             // 单个路由的最大连接数
                );

        RestClient client = builder.build();
        ElasticsearchTransport transport = new RestClientTransport(client, new JacksonJsonpMapper());
        return new ElasticsearchClient(transport);
    }
}
