首页  编辑  

Java SpringBoot SSL连接Elasticsearch

Tags: /Java/   Date Created:

SpringBoot中通过SSL连接Elasticsearch的方法

修改 application.properties

修改app配置,增加相关配置:

elasticsearch.host=es-server
elasticsearch.port=9400
elasticsearch.username=username
elasticsearch.password=ENC(eAwrhIAM7RtseR7DP1jylnkfxtsXgfj8d+BfWlr+ChE=)

增加Configuration对象

增加ElasticsearchConfig.java,代码如下:

package hk.xxx.xxx.config;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.net.ssl.SSLContext;

@Data
@Slf4j
@Configuration
@ConfigurationProperties(prefix = "elasticsearch")
public class ElasticsearchConfig {

    private String host;
    private Integer port;
    private String password;
    private String username;

    @Bean
    public RestHighLevelClient elasticsearchClient() throws Exception {
        try {
            BasicCredentialsProvider provider = new BasicCredentialsProvider();
            provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

            SSLContextBuilder sslBuilder = SSLContexts.custom()
                    .loadTrustMaterial(null, (x509Certificates, s) -> true);
            final SSLContext sslContext = sslBuilder.build();
            RestHighLevelClient client = new RestHighLevelClient(RestClient
                    .builder(new HttpHost(host, port, "https"))
                    .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder
                            .setDefaultCredentialsProvider(provider)
                            .setSSLContext(sslContext)
                            .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE))
                    .setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder.setConnectTimeout(5000)
                            .setSocketTimeout(120000)));
            return client;
        } catch (Exception e) {
            log.error("Create elasticsearch client error: " + e.getMessage());
            throw new Exception("Create elasticsearch client error: " + e.getMessage());
        }
    }
}
此后,就可以正常使用了:
@Autowired
private RestHighLevelClient client;