You can access a CSS cluster using Spring Boot. Spring Boot can connect to a cluster in any of the following ways:
For details about how to use Spring Boot, see the official document: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/
7.10.2 indicates the version of the Elasticsearch Java client.
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.5.5</version></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId></dependency><dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId><version>7.10.2</version></dependency></dependencies>
This scenario applies to clusters in non-security mode or clusters in security mode+HTTP.
Configuration file:
1234elasticsearch.url=host1:9200,host2:9200// You do not need to configure the following two lines for a non-security cluster.elasticsearch.username=usernameelasticsearch.password=password
Parameter | Description |
|---|---|
host | IP address for accessing the Elasticsearch cluster. |
username | Username for accessing the cluster. |
password | Password of the user. |
Code:
12345678910111213141516171819202122232425262728293031323334353637383940414243package com.xxx.configuration;import org.elasticsearch.client.RestHighLevelClient;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.data.elasticsearch.client.ClientConfiguration;import org.springframework.data.elasticsearch.client.RestClients;import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;@Configuration@EnableElasticsearchRepositories(basePackages = "com.xxx.repository")@ComponentScan(basePackages = "com.xxx")public class Config extends AbstractElasticsearchConfiguration {@Value("${elasticsearch.url}")public String elasticsearchUrl;// You do not need to set the following two parameters for a non-security cluster.@Value("${elasticsearch.username}")public String elasticsearchUsername;@Value("${elasticsearch.password}")public String elasticsearchPassword;@Override@Beanpublic RestHighLevelClient elasticsearchClient() {final ClientConfiguration clientConfiguration = ClientConfiguration.builder().connectedTo(StringHostParse(elasticsearchUrl))// For a non-security cluster, there is no need to configure withBasicAuth..withBasicAuth(elasticsearchUsername, elasticsearchPassword).build();return RestClients.create(clientConfiguration).rest();}private String[] StringHostParse(String hostAndPorts) {return hostAndPorts.split(",");}}
You can connect to a cluster in Security mode + HTTPS without using any security certificate.
Configuration file:
123elasticsearch.url=host1:9200,host2:9200elasticsearch.username=usernameelasticsearch.password=password
Parameter | Description |
|---|---|
host | IP address for accessing the Elasticsearch cluster. |
username | Username for accessing the cluster. |
password | Password of the user. |
Code:
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071package com.xxx.configuration;import org.elasticsearch.client.RestHighLevelClient;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.data.elasticsearch.client.ClientConfiguration;import org.springframework.data.elasticsearch.client.RestClients;import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;import java.security.KeyManagementException;import java.security.NoSuchAlgorithmException;import java.security.SecureRandom;import java.security.cert.CertificateException;import java.security.cert.X509Certificate;import javax.net.ssl.HostnameVerifier;import javax.net.ssl.SSLContext;import javax.net.ssl.SSLSession;import javax.net.ssl.TrustManager;import javax.net.ssl.X509TrustManager;@Configuration@EnableElasticsearchRepositories(basePackages = "com.xxx.repository")@ComponentScan(basePackages = "com.xxx")public class Config extends AbstractElasticsearchConfiguration {@Value("${elasticsearch.url}")public String elasticsearchUrl;@Value("${elasticsearch.username}")public String elasticsearchUsername;@Value("${elasticsearch.password}")public String elasticsearchPassword;@Override@Beanpublic RestHighLevelClient elasticsearchClient() {SSLContext sc = null;try {sc = SSLContext.getInstance("SSL");sc.init(null, trustAllCerts, new SecureRandom());} catch (KeyManagementException | NoSuchAlgorithmException e) {e.printStackTrace();}final ClientConfiguration clientConfiguration = ClientConfiguration.builder().connectedTo(StringHostParse(elasticsearchUrl)).usingSsl(sc, new NullHostNameVerifier()).withBasicAuth(elasticsearchUsername, elasticsearchPassword).build();return RestClients.create(clientConfiguration).rest();}private String[] StringHostParse(String hostAndPorts) {return hostAndPorts.split(",");}public static TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {@Overridepublic void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}@Overridepublic void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}@Overridepublic X509Certificate[] getAcceptedIssuers() {return null;}}};public static class NullHostNameVerifier implements HostnameVerifier {@Overridepublic boolean verify(String arg0, SSLSession arg1) {return true;}}}
You can use a security certificate to connect to a cluster in security mode + HTTPS.
123elasticsearch.url=host1:9200,host2:9200elasticsearch.username=usernameelasticsearch.password=password
Parameter | Description |
|---|---|
host | IP address for accessing the Elasticsearch cluster. |
username | Username for accessing the cluster. |
password | Password of the user. |
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596package com.xxx.configuration;import org.elasticsearch.client.RestHighLevelClient;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.data.elasticsearch.client.ClientConfiguration;import org.springframework.data.elasticsearch.client.RestClients;import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;import java.io.File;import java.io.FileInputStream;import java.io.InputStream;import java.security.KeyStore;import java.security.SecureRandom;import java.security.cert.CertificateException;import java.security.cert.X509Certificate;import javax.net.ssl.HostnameVerifier;import javax.net.ssl.SSLContext;import javax.net.ssl.SSLSession;import javax.net.ssl.TrustManager;import javax.net.ssl.TrustManagerFactory;import javax.net.ssl.X509TrustManager;@Configuration@EnableElasticsearchRepositories(basePackages = "com.xxx.repository")@ComponentScan(basePackages = "com.xxx")public class Config extends AbstractElasticsearchConfiguration {@Value("${elasticsearch.url}")public String elasticsearchUrl;@Value("${elasticsearch.username}")public String elasticsearchUsername;@Value("${elasticsearch.password}")public String elasticsearchPassword;@Override@Beanpublic RestHighLevelClient elasticsearchClient() {SSLContext sc = null;try {TrustManager[] tm = {new MyX509TrustManager(certFilePath, certPassword)};sc = SSLContext.getInstance("SSL", "SunJSSE");sc.init(null, tm, new SecureRandom());} catch (Exception e) {e.printStackTrace();}final ClientConfiguration clientConfiguration = ClientConfiguration.builder().connectedTo(StringHostParse(elasticsearchUrl)).usingSsl(sc, new NullHostNameVerifier()).withBasicAuth(elasticsearchUsername, elasticsearchPassword).build();return RestClients.create(clientConfiguration).rest();}private String[] StringHostParse(String hostAndPorts) {return hostAndPorts.split(",");}public static class MyX509TrustManager implements X509TrustManager {X509TrustManager sunJSSEX509TrustManager;MyX509TrustManager(String certFilePath, String certPassword) throws Exception {File file = new File(certFilePath);if (!file.isFile()) {throw new Exception("Wrong Certification Path");}System.out.println("Loading KeyStore " + file + "...");InputStream in = new FileInputStream(file);KeyStore ks = KeyStore.getInstance("JKS");ks.load(in, certPassword.toCharArray());TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509", "SunJSSE");tmf.init(ks);TrustManager[] tms = tmf.getTrustManagers();for (TrustManager tm : tms) {if (tm instanceof X509TrustManager) {sunJSSEX509TrustManager = (X509TrustManager) tm;return;}}throw new Exception("Couldn't initialize");}@Overridepublic void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}@Overridepublic void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}@Overridepublic X509Certificate[] getAcceptedIssuers() {return new X509Certificate[0];}}public static class NullHostNameVerifier implements HostnameVerifier {@Overridepublic boolean verify(String arg0, SSLSession arg1) {return true;}}}
In the preceding command, certFilePath and certPassword indicate the path and password of the .jks certificate, respectively.
To access a security-mode Elasticsearch cluster that uses HTTPS, a security certificate must be loaded. Perform the following steps to obtain the security certificate and upload it to the client:
keytool -import -alias newname -keystore ./truststore.jks -file ./CloudSearchService.cer
keytool -import -alias newname -keystore .\truststore.jks -file .\CloudSearchService.cer
In the preceding command, newname indicates the user-defined certificate name.
After this command is executed, you will be prompted to set the certificate password and confirm the password. Securely store the password. It will be used for accessing the cluster.