package com.yeejoin.equip.utils;

import com.yeejoin.equip.config.ElasticSearchConfig;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import java.time.Duration;
import java.util.Objects;

/**
 * ElasticSearch 配置
 * @author LiuLin
 * @date 2023年08月08日 16:30
 */
@Slf4j
@Configuration
public class ElasticSearchClient {

    @Autowired(required = false)
    private ElasticSearchConfig elasticSearchConfig;

    @Bean
    public RestHighLevelClient client() {
        ClientConfiguration clientConfiguration = null;
        try {
            clientConfiguration = ClientConfiguration.builder()
                    .connectedTo(elasticSearchConfig.getAddress())
                    .withConnectTimeout(Duration.ofSeconds(5))
                    .withSocketTimeout(Duration.ofSeconds(3))
                    .withSocketTimeout(elasticSearchConfig.getSocketTimeout())
                    .withConnectTimeout(elasticSearchConfig.getConnectTimeout())
                    .withBasicAuth(elasticSearchConfig.getUsername(), elasticSearchConfig.getPassword())
                    .build();
        }catch (Exception e){
            log.error("连接ES异常" + e.getMessage(), e);
        }
        return RestClients.create(Objects.requireNonNull(clientConfiguration)).rest();
    }
}