ESConfig.java 1.96 KB
Newer Older
张辰's avatar
张辰 committed
1 2
package com.tanpu.community.config;

张辰's avatar
张辰 committed
3
import lombok.Data;
张辰's avatar
张辰 committed
4
import lombok.extern.slf4j.Slf4j;
张辰's avatar
张辰 committed
5 6 7 8 9 10 11 12 13 14
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.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
张辰's avatar
张辰 committed
15
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
张辰's avatar
张辰 committed
16 17 18 19 20
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

张辰's avatar
张辰 committed
21
@Slf4j
张辰's avatar
张辰 committed
22 23 24
@Data
@Component
@ConfigurationProperties(prefix = "es")
张辰's avatar
张辰 committed
25 26 27 28 29 30 31 32 33 34 35 36 37
public class ESConfig {

    private String userName;
    private String userPasswd;
    private String host;
    private Integer port;

    @Bean
    public RestHighLevelClient client() {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, userPasswd));

        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(
张辰's avatar
张辰 committed
38
                RestClient.builder(new HttpHost(host, port, "http")).setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
张辰's avatar
张辰 committed
39 40 41 42 43
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                        return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    }
                }));
张辰's avatar
张辰 committed
44 45

        log.info("es client created. addr: {}:{}, userName: {}", host, port, userName);
张辰's avatar
张辰 committed
46 47 48
        return restHighLevelClient;
    }
}