Elasticsearch предоставляет SDK (High Level REST Client) для подключения к кластеру. Этот клиент инкапсулирует API Elasticsearch. Вам необходимо лишь сформировать требуемые структуры для доступа к кластеру Elasticsearch. Подробнее о том, как использовать Rest Client, см. официальную документацию по адресу https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high.html.
В этом разделе описывается, как использовать High Level REST Client для доступа к кластеру CSS. High Level REST Client можно подключить к кластеру одним из следующих способов:
Версия High Level REST Client должна соответствовать версии Elasticsearch. Например, используйте High Level REST Client 7.6.2 для доступа к кластеру Elasticsearch 7.6.2. Если версия вашего Java High Level REST Client новее кластера Elasticsearch и возникают проблемы совместимости с некоторыми запросами, вы можете использовать RestHighLevelClient.getLowLevelClient() для получения Low Level Client и настройки содержимого запросов Elasticsearch.
7.6.2 указывает версию клиента Elasticsearch Java.
<dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId><version>7.6.2</version></dependency><dependency><groupId>org.elasticsearch</groupId><artifactId>elasticsearch</artifactId><version>7.6.2</version></dependency>
compile group: 'org.elasticsearch.client', name: 'elasticsearch-rest-high-level-client', version: '7.6.2'
Используйте High Level REST Client для подключения к кластеру в режиме без безопасности и проверьте, тест индекс существует. Пример кода приведён ниже:
1234567891011121314151617181920212223242526272829303132import org.apache.http.HttpHost;import org.elasticsearch.client.RequestOptions;import org.elasticsearch.client.RestClient;import org.elasticsearch.client.RestClientBuilder;import org.elasticsearch.client.RestHighLevelClient;import org.elasticsearch.client.indices.GetIndexRequest;import java.io.IOException;import java.util.Arrays;import java.util.List;/*** Используйте Rest Hive Level для подключения к кластеру без безопасности.*/public class Main {public static void main(String[] args) throws IOException {List<String> host = Arrays.asList("xx.xx.xx.xx", "xx.xx.xx.xx");RestClientBuilder builder = RestClient.builder(constructHttpHosts(host, 9200, "http"));final RestHighLevelClient client = new RestHighLevelClient(builder);GetIndexRequest indexRequest = new GetIndexRequest("test");boolean exists = client.indices().exists(indexRequest, RequestOptions.DEFAULT);System.out.println(exists);client.close();}/*** Используйте функцию constructHttpHosts для преобразования списка IP‑адресов узлов хост‑кластера.*/public static HttpHost[] constructHttpHosts(List<String> host, int port, String protocol) {return host.stream().map(p -> new HttpHost(p, порт, протокол)).toArray(HttpHost[]::new);}}
хост указывает IP‑адрес кластера. Если указано несколько IP‑адресов, разделите их запятыми (,). тест указывает имя индекса для запроса.
Подключитесь к кластеру в режиме безопасности, который использует HTTP или HTTPS без использования сертификата безопасности.
Пример кода выглядит следующим образом:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171import 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.apache.http.nio.conn.ssl.SSLIOSessionStrategy;import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;import org.elasticsearch.client.RequestOptions;import org.elasticsearch.client.RestClient;import org.elasticsearch.client.RestClientBuilder;import org.elasticsearch.client.RestHighLevelClient;import org.elasticsearch.client.indices.GetIndexRequest;импорт org.elasticsearch.common.Nullable;импорт java.io.IOException;импорт java.security.KeyManagementException;импорт java.security.NoSuchAlgorithmException;импорт java.security.SecureRandom;импорт java.security.cert.CertificateException;импорт java.security.cert.X509Certificate;импорт java.util.Arrays;импорт java.util.List;импорт java.util.Objects;импорт javax.net.ssl.HostnameVerifier;импорт javax.net.ssl.SSLContext;импорт javax.net.ssl.SSLSession;импорт javax.net.ssl.TrustManager;импорт javax.net.ssl.X509TrustManager;/*** Подключитесь к кластеру безопасности через Rest High Level (без использования сертификатов).*/public class Main {/*** Создайте класс для клиента. Определите функцию create.*/public static RestHighLevelClient create(List<String> host, int port, String protocol, int connectTimeout, int connectionRequestTimeout, int socketTimeout, String username, String password) throws IOException{final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));SSLContext sc = null;try {sc = SSLContext.getInstance("SSL");sc.init(null, trustAllCerts, new SecureRandom());} catch (KeyManagementException | NoSuchAlgorithmException e) {e.printStackTrace();}SSLIOSessionStrategy sessionStrategy = new SSLIOSessionStrategy(sc, new NullHostNameVerifier());SecuredHttpClientConfigCallback httpClientConfigCallback = new SecuredHttpClientConfigCallback(sessionStrategy,credentialsProvider);RestClientBuilder builder = RestClient.builder(constructHttpHosts(host, port, protocol)).setRequestConfigCallback(requestConfig -> requestConfig.setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectionRequestTimeout).setSocketTimeout(socketTimeout)).setHttpClientConfigCallback(httpClientConfigCallback);final RestHighLevelClient client = new RestHighLevelClient(builder);logger.info("es rest client build success {} ", client);ClusterHealthRequest request = new ClusterHealthRequest();ClusterHealthResponse response = client.cluster().health(request, RequestOptions.DEFAULT);logger.info("es rest client health response {} ", response);return client;}/*** Используйте функцию constructHttpHosts для преобразования списка IP‑адресов узлов хост‑кластера.*/public static HttpHost[] constructHttpHosts(List<String> host, int port, String protocol) {return Хост.поток().map(p -> new HttpHost(p, порт, протокол)).toArray(HttpHost[]::new);}/*** Настройте trustAllCerts, чтобы игнорировать конфигурацию сертификата.*/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;}}};private static final Logger logger = LogManager.getLogger(Main.class);static class SecuredHttpClientConfigCallback implements RestClientBuilder.HttpClientConfigCallback {@Nullableprivate final CredentialsProvider credentialsProvider;/*** {@link SSLIOSessionStrategy} для всех запросов, чтобы включить шифрование SSL / TLS.*/private final SSLIOSessionStrategy sslStrategy;/*** Создать новый {@link SecuredHttpClientConfigCallback}.** @param credentialsProvider Провайдер учетных данных, если указаны имя пользователя/пароль* @param sslStrategy SSL‑стратегия, если SSL / TLS были предоставлены* @throws NullPointerException если {@code sslStrategy} равен {@code null}*/SecuredHttpClientConfigCallback(final SSLIOSessionStrategy sslStrategy,@Nullable final CredentialsProvider credentialsProvider) {this.sslStrategy = Objects.requireNonNull(sslStrategy);this.credentialsProvider = credentialsProvider;}/*** Получить {@link CredentialsProvider}, который будет добавлен к HTTP client.** @return Может быть {@code null}.*/@NullableCredentialsProvider getCredentialsProvider() {return credentialsProvider;}/*** Получить {@link SSLIOSessionStrategy}, который будет добавлен в HTTP клиент.** @return Никогда {@code null}.*/SSLIOSessionStrategy getSSLStrategy() {return sslStrategy;}/*** Устанавливает {@linkplain HttpAsyncClientBuilder#setDefaultCredentialsProvider(CredentialsProvider) провайдер учетных данных},** @param httpClientBuilder Клиент для настройки.* @return Всегда {@code httpClientBuilder}.*/@Overridepublic HttpAsyncClientBuilder customizeHttpClient(final HttpAsyncClientBuilder httpClientBuilder) {// включить SSL / TLShttpClientBuilder.setSSLStrategy(sslStrategy);// enable user authenticationif (credentialsProvider != null) {httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);}return httpClientBuilder;}}public static class NullHostNameVerifier implements HostnameVerifier {@Overridepublic boolean verify(String arg0, SSLSession arg1) {return true;}}/*** Следующее является примером основной функции. Вызовите функцию create, чтобы создать клиент и проверить, существует ли тестовый индекс.*/public static void main(String[] args) throws IOException {RestHighLevelClient client = create(Arrays.asList("xx.xx.xx.xx", "xx.xx.xx.xx"), 9200, "https", 1000, 1000, 1000, "username", "password");GetIndexRequest indexRequest = new GetIndexRequest("test");boolean exists = клиент.индексы().существует(indexRequest, RequestOptions.DEFAULT);System.out.println(существует);клиент.close();}}
Параметр | Описание |
|---|---|
host | IP-адрес для доступа к кластеру Elasticsearch. Если указано несколько IP-адресов, разделите их запятыми (,). |
port | Порт доступа к кластеру Elasticsearch. Значение по умолчанию — 9200. |
protocol | Протокол соединения, который может быть http или https. |
connectTimeout | Таймаут сокетного соединения (в мс). |
connectionRequestTimeout | Таймаут запроса сокетного соединения (в мс). |
socketTimeout | Тайм-аут запроса сокета (в мс). |
username | Имя пользователя для доступа к кластеру. |
password | Пароль пользователя. |
Подключитесь к кластеру Elasticsearch в режиме безопасности, использующему HTTPS с сертификатом безопасности. Пример кода выглядит следующим образом:
Как получить и загрузить сертификат безопасности, см. Получение и загрузка сертификата безопасности.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167import 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.conn.ssl.NoopHostnameVerifier;import org.apache.http.impl.client.BasicCredentialsProvider;import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;import org.apache.http.nio.conn.ssl.SSLIOSessionStrategy;import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;import org.elasticsearch.client.RequestOptions;import org.elasticsearch.client.RestClient;import org.elasticsearch.client.RestClientBuilder;import org.elasticsearch.client.RestHighLevelClient;import org.elasticsearch.client.indices.GetIndexRequest;import org.elasticsearch.common.Nullable;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.security.KeyStore;import java.security.SecureRandom;import java.security.cert.CertificateException;import java.security.cert.X509Certificate;import java.util.Arrays;import java.util.List;import java.util.Objects;import javax.net.ssl.SSLContext;import javax.net.ssl.TrustManager;import javax.net.ssl.TrustManagerFactory;import javax.net.ssl.X509TrustManager;/*** Используйте Rest Hive Level для подключения к безопасному кластеру (с использованием HTTPS сертификата).*/public class Main {public static RestHighLevelClient create(List<String> host, int port, String protocol, int connectTimeout, int connectionRequestTimeout, int socketTimeout, String username, String password, String certFilePath,String certPassword) throws IOException {final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));SSLContext sc = null;try {TrustManager[] tm = {new MyX509TrustManager(certFilePath, certPassword)};sc = SSLContext.getInstance("SSL", "SunJSSE");//Вы также можете использовать SSLContext sslContext = SSLContext.getInstance("TLSv1.2");sc.init(null, tm, new SecureRandom());} catch (Exception e) {e.printStackTrace();}SSLIOSessionStrategy sessionStrategy = new SSLIOSessionStrategy(sc, new NoopHostnameVerifier());SecuredHttpClientConfigCallback httpClientConfigCallback = new SecuredHttpClientConfigCallback(sessionStrategy,credentialsProvider);RestClientBuilder builder = RestClient.builder(constructHttpHosts(host, port, протокол)).setRequestConfigCallback(requestConfig -> requestConfig.setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectionRequestTimeout).setSocketTimeout(socketTimeout)).setHttpClientConfigCallback(httpClientConfigCallback);final RestHighLevelClient client = new RestHighLevelClient(builder);logger.info("es rest client build success {} ", client);ClusterHealthRequest request = new ClusterHealthRequest();ClusterHealthResponse response = client.cluster().health(request, RequestOptions.DEFAULT);logger.info("es rest client health response {} ", ответ);вернуть клиент;}/*** Используйте функцию constructHttpHosts для преобразования списка IP‑адресов узлов кластера хостов.*/public static HttpHost[] constructHttpHosts(List<String> host, int port, Строка протокол) {return хост.стрим().map(p -> new HttpHost(p, порт, протокол)).toArray(HttpHost[]::new);}/*** SecuredHttpClientConfigCallback определение класса*/static class SecuredHttpClientConfigCallback implements RestClientBuilder.HttpClientConfigCallback {@Nullableprivate final CredentialsProvider credentialsProvider;private final SSLIOSessionStrategy sslStrategy;SecuredHttpClientConfigCallback(final SSLIOSessionStrategy sslStrategy,@Nullable final CredentialsProvider credentialsProvider) {this.sslStrategy = Objects.requireNonNull(sslStrategy);this.credentialsProvider = credentialsProvider;}@NullableCredentialsProvider getCredentialsProvider() {return credentialsProvider;}SSLIOSessionStrategy getSSLStrategy() {return sslStrategy;}@Overridepublic HttpAsyncClientBuilder customizeHttpClient(final HttpAsyncClientBuilder httpClientBuilder) {httpClientBuilder.setSSLStrategy(sslStrategy);if (credentialsProvider != null) {httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);}return httpClientBuilder;}}private static final Logger logger = LogManager.getLogger(Main.class);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("Неправильный путь сертификата");}System.out.println("Загрузка 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];}}/*** Следующий пример основной функции. Вызовите функцию create, чтобы создать клиент и проверить, существует ли тестовый индекс.*/public static void main(String[] args) throws IOException {RestHighLevelClient client = create(Arrays.asList("xxx.xxx.xxx.xxx", "xxx.xxx.xxx.xxx"), 9200, "https", 1000, 1000, 1000, "username", "password", "certFilePath", "certPassword");GetIndexRequest indexRequest = new GetIndexRequest("test");boolean exists = клиент.индексы().существует(indexRequest, RequestOptions.DEFAULT);System.out.println(существует);клиент.close();}}
Параметр | Описание |
|---|---|
Хост | IP‑адрес для доступа к кластеру Elasticsearch. Если указано несколько IP‑адресов, разделите их запятыми (,). |
port | Порт доступа к кластеру Elasticsearch. Значение по умолчанию 9200. |
протокол | Протокол соединения. Установите этот параметр в https. |
connectTimeout | Тайм‑аут сокет‑соединения (в мс). |
connectionRequestTimeout | Тайм‑аут запроса сокет‑соединения (в мс). |
socketTimeout | Тайм‑аут сокет‑запроса (в мс). |
имя пользователя | Имя пользователя для доступа к кластеру. |
пароль | Пароль пользователя. |
certFilePath | Путь к сертификату. |
certPassword | Пароль сертификата. |
Для доступа к кластеру Elasticsearch в режиме security, использующему HTTPS, необходимо загрузить сертификат безопасности. Выполните следующие шаги, чтобы получить сертификат безопасности и загрузить его в клиент:
keytool -import -alias newname -keystore ./truststore.jks -file ./CloudSearchService.cer
keytool -import -alias newname -keystore .\truststore.jks -file .\CloudSearchService.cer
В предыдущей команде, newname указывает пользовательское имя сертификата.
После выполнения этой команды вам будет предложено задать пароль сертификата и подтвердить его. Надёжно сохраните пароль. Он будет использоваться для доступа к кластеру.