Elasticsearch 入门实战(4)--Java Low Level REST Client 使用
本文主要介绍 Elasticsearch Java Low Level REST Client 的使用,相关的环境及软件信息如下:CentOS 7.6.1810、Java 1.8.0_321(客户端用)、Elasticsearch 8.2.2。
1、Java Low Level REST Client 的特点
- minimal dependencies
- load balancing across all available nodes
- failover in case of node failures and upon specific response codes
- failed connection penalization (whether a failed node is retried depends on how many consecutive times it failed; the more failed attempts the longer the client will wait before trying that same node again)
- persistent connections
- trace logging of requests and responses
- optional automatic discovery of cluster nodes
2、引入依赖
<dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-client</artifactId> <version>8.2.2</version> </dependency>
3、使用
Java Low Level REST Client 主要工作是组装 JSON 格式的请求数据,其他都是些通用的配置;请求数据的详细说明可参考:Elasticsearch 入门实战(3)--REST API 使用。
3.1、Elasticsearch 关闭了安全认证,使用 HTTP 协议访问
@Test public void http() { RestClient restClient = null; try { RestClientBuilder builder = RestClient.builder( new HttpHost("10.49.196.10", 9200), new HttpHost("10.49.196.11", 9200), new HttpHost("10.49.196.12", 9200)); //设置失败监听器 builder.setFailureListener(new RestClient.FailureListener() { @Override public void onFailure(Node node) { logger.info("失败:node={}", node); } }); //设置请求头 Header[] defaultHeaders = new Header[]{new BasicHeader("head-a", "123")}; builder.setDefaultHeaders(defaultHeaders); //设置节点选择器 builder.setNodeSelector(NodeSelector.SKIP_DEDICATED_MASTERS); //设置请求配置回调方法 builder.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() { @Override public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder builder) { return builder.setSocketTimeout(1000 * 5); } }); //用户名密码 CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "123456")); //设置HttpClient配置回调方法 builder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() { @Override public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) { return httpAsyncClientBuilder.setUserAgent("elasticseatch-rest-client").setDefaultCredentialsProvider(credentialsProvider); } }); restClient = builder.build(); //请求对象 Request request = new Request("GET", "/poet-index/_search"); request.addParameter("pretty", "true"); //请求体,json数据 String body = "{\n" + " \"query\": {\n" + " \"match\": {\n" + " \"success\": \"思想\"\n" + " }\n" + " },\n" + " \"from\": 0,\n" + " \"size\": 10\n" + "}"; request.setEntity(new NStringEntity(body, ContentType.APPLICATION_JSON)); Response response = restClient.performRequest(request); logger.info("requestLine={}", response.getRequestLine()); logger.info("host={}", response.getHost()); logger.info("statusCode={}", response.getStatusLine().getStatusCode()); logger.info("headers={}", response.getHeaders()); logger.info("responseBody={}", EntityUtils.toString(response.getEntity())); } catch (Exception e) { e.printStackTrace(); } finally { if (restClient != null) { try { restClient.close(); } catch (IOException e) { e.printStackTrace(); } } } }
3.2、Elasticsearch 开启了安全认证,使用 HTTPS 协议访问
@Test public void https() { RestClient restClient = null; try { RestClientBuilder builder = RestClient.builder( new HttpHost("10.49.196.10", 9200, "https"), new HttpHost("10.49.196.11", 9200, "https"), new HttpHost("10.49.196.12", 9200, "https")); //设置失败监听器 builder.setFailureListener(new RestClient.FailureListener() { @Override public void onFailure(Node node) { logger.info("失败:node={}", node); } }); //设置请求头 Header[] defaultHeaders = new Header[]{new BasicHeader("head-a", "123")}; builder.setDefaultHeaders(defaultHeaders); //设置节点选择器 builder.setNodeSelector(NodeSelector.SKIP_DEDICATED_MASTERS); //设置请求配置回调方法 builder.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() { @Override public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder builder) { return builder.setSocketTimeout(1000 * 5); } }); //用户名密码 CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "123456")); //设置HttpClient配置回调方法 builder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() { @Override public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) { return httpAsyncClientBuilder.setUserAgent("elasticseatch-rest-client") .setDefaultCredentialsProvider(credentialsProvider) .setSSLContext(getSSLContext()); } }); restClient = builder.build(); //请求对象 Request request = new Request("GET", "/poet-index/_search"); request.addParameter("pretty", "true"); //请求体,json数据 String body = "{\n" + " \"query\": {\n" + " \"match\": {\n" + " \"success\": \"思想\"\n" + " }\n" + " },\n" + " \"from\": 0,\n" + " \"size\": 10\n" + "}"; request.setEntity(new NStringEntity(body, ContentType.APPLICATION_JSON)); Response response = restClient.performRequest(request); logger.info("requestLine={}", response.getRequestLine()); logger.info("host={}", response.getHost()); logger.info("statusCode={}", response.getStatusLine().getStatusCode()); logger.info("headers={}", response.getHeaders()); logger.info("responseBody={}", EntityUtils.toString(response.getEntity())); } catch (Exception e) { e.printStackTrace(); } finally { if (restClient != null) { try { restClient.close(); } catch (IOException e) { e.printStackTrace(); } } } }
3.3、完整代码
package com.abc.demo.es; import org.apache.http.Header; 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.client.config.RequestConfig; import org.apache.http.conn.ssl.TrustAllStrategy; import org.apache.http.entity.ContentType; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.nio.client.HttpAsyncClientBuilder; import org.apache.http.message.BasicHeader; import org.apache.http.nio.entity.NStringEntity; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.SSLContexts; import org.apache.http.util.EntityUtils; import org.elasticsearch.client.*; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.SSLContext; import java.io.IOException; public class ElasticseatchRestClientCase { private static final Logger logger = LoggerFactory.getLogger(ElasticseatchRestClientCase.class.getName()); @Test public void http() { RestClient restClient = null; try { RestClientBuilder builder = RestClient.builder( new HttpHost("10.49.196.10", 9200), new HttpHost("10.49.196.11", 9200), new HttpHost("10.49.196.12", 9200)); //设置失败监听器 builder.setFailureListener(new RestClient.FailureListener() { @Override public void onFailure(Node node) { logger.info("失败:node={}", node); } }); //设置请求头 Header[] defaultHeaders = new Header[]{new BasicHeader("head-a", "123")}; builder.setDefaultHeaders(defaultHeaders); //设置节点选择器 builder.setNodeSelector(NodeSelector.SKIP_DEDICATED_MASTERS); //设置请求配置回调方法 builder.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() { @Override public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder builder) { return builder.setSocketTimeout(1000 * 5); } }); //用户名密码 CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "123456")); //设置HttpClient配置回调方法 builder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() { @Override public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) { return httpAsyncClientBuilder.setUserAgent("elasticseatch-rest-client").setDefaultCredentialsProvider(credentialsProvider); } }); restClient = builder.build(); //请求对象 Request request = new Request("GET", "/poet-index/_search"); request.addParameter("pretty", "true"); //请求体,json数据 String body = "{\n" + " \"query\": {\n" + " \"match\": {\n" + " \"success\": \"思想\"\n" + " }\n" + " },\n" + " \"from\": 0,\n" + " \"size\": 10\n" + "}"; request.setEntity(new NStringEntity(body, ContentType.APPLICATION_JSON)); Response response = restClient.performRequest(request); logger.info("requestLine={}", response.getRequestLine()); logger.info("host={}", response.getHost()); logger.info("statusCode={}", response.getStatusLine().getStatusCode()); logger.info("headers={}", response.getHeaders()); logger.info("responseBody={}", EntityUtils.toString(response.getEntity())); } catch (Exception e) { e.printStackTrace(); } finally { if (restClient != null) { try { restClient.close(); } catch (IOException e) { e.printStackTrace(); } } } } @Test public void https() { RestClient restClient = null; try { RestClientBuilder builder = RestClient.builder( new HttpHost("10.49.196.10", 9200, "https"), new HttpHost("10.49.196.11", 9200, "https"), new HttpHost("10.49.196.12", 9200, "https")); //设置失败监听器 builder.setFailureListener(new RestClient.FailureListener() { @Override public void onFailure(Node node) { logger.info("失败:node={}", node); } }); //设置请求头 Header[] defaultHeaders = new Header[]{new BasicHeader("head-a", "123")}; builder.setDefaultHeaders(defaultHeaders); //设置节点选择器 builder.setNodeSelector(NodeSelector.SKIP_DEDICATED_MASTERS); //设置请求配置回调方法 builder.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() { @Override public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder builder) { return builder.setSocketTimeout(1000 * 5); } }); //用户名密码 CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "123456")); //设置HttpClient配置回调方法 builder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() { @Override public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) { return httpAsyncClientBuilder.setUserAgent("elasticseatch-rest-client") .setDefaultCredentialsProvider(credentialsProvider) .setSSLContext(getSSLContext()); } }); restClient = builder.build(); //请求对象 Request request = new Request("GET", "/poet-index/_search"); request.addParameter("pretty", "true"); //请求体,json数据 String body = "{\n" + " \"query\": {\n" + " \"match\": {\n" + " \"success\": \"思想\"\n" + " }\n" + " },\n" + " \"from\": 0,\n" + " \"size\": 10\n" + "}"; request.setEntity(new NStringEntity(body, ContentType.APPLICATION_JSON)); Response response = restClient.performRequest(request); logger.info("requestLine={}", response.getRequestLine()); logger.info("host={}", response.getHost()); logger.info("statusCode={}", response.getStatusLine().getStatusCode()); logger.info("headers={}", response.getHeaders()); logger.info("responseBody={}", EntityUtils.toString(response.getEntity())); } catch (Exception e) { e.printStackTrace(); } finally { if (restClient != null) { try { restClient.close(); } catch (IOException e) { e.printStackTrace(); } } } } private SSLContext getSSLContext() { try { SSLContextBuilder bulider = SSLContexts.custom(); bulider.loadTrustMaterial(new TrustAllStrategy()); return bulider.build(); } catch (Exception e) { e.printStackTrace(); } return null; } }
详细的 Elasticsearch Java Low Level REST Client 使用说明,看参考官网文档:https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/current/java-rest-low.html。