文章目录
- 1 背景
- 2 前言
- 3 Java如何操作ES
- 3.1 引入依赖
- 3.2 依赖介绍
- 3.3 隐藏依赖
- 3.4 初始化客户端(获取ES连接)
- 3.5 发送请求给ES
1 背景
上篇学习了0基础学习Elasticsearch-Quick start,随后本篇研究如何使用Java操作ES
2 前言
- 建议通篇阅读再回头来跟着敲代码
- 建议先阅读Java连接ES云以及如何使用CA证书连接、ES鉴权连接对Java连接ES有哪几种方法有个认知,阅读如何Reading responses,阅读如何同步、异步发送请求
- ES 8版本后建议使用
Java Low Level REST Client
Java客户端,本篇采用该客户端
3 Java如何操作ES
3.1 引入依赖
<dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-client</artifactId><version>8.13.4</version>
</dependency>
3.2 依赖介绍
low-level Java REST client
内部采用了Apache Http Async Client
来发送HTTP请求,内部含有以下这些依赖,如果遇到依赖冲突,需要解决:
- org.apache.httpcomponents:httpasyncclient
- org.apache.httpcomponents:httpcore-nio
- org.apache.httpcomponents:httpclient
- org.apache.httpcomponents:httpcore
- commons-codec:commons-codec
- commons-logging:commons-logging
3.3 隐藏依赖
如果遇到上面列出的依赖冲突,可以使用下面这个方法来解决,pom文件加入下面代码:
<build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-shade-plugin</artifactId><version>3.1.0</version><executions><execution><phase>package</phase><goals><goal>shade</goal></goals><configuration><relocations><relocation><pattern>org.apache.http</pattern><shadedPattern>hidden.org.apache.http</shadedPattern></relocation><relocation><pattern>org.apache.logging</pattern><shadedPattern>hidden.org.apache.logging</shadedPattern></relocation><relocation><pattern>org.apache.commons.codec</pattern><shadedPattern>hidden.org.apache.commons.codec</shadedPattern></relocation><relocation><pattern>org.apache.commons.logging</pattern><shadedPattern>hidden.org.apache.commons.logging</shadedPattern></relocation></relocations></configuration></execution></executions></plugin></plugins>
</build>
3.4 初始化客户端(获取ES连接)
概括:通过账号密码来获取连接。笔者这里通过注入bean的方式初始化ES客户端并交给Spring管理
@Slf4j
@Configuration
public class EsClient {public static final String HOST = "192.168.90.128";public static final int PORT = 9200;public static final String PROTOCOL = "https";public static final String username = "elastic";public static final String password = "84fZ4PuywWr_unOcr+JH";@Beanpublic RestClient restClient() {RestClientBuilder clientBuilder = RestClient.builder(new HttpHost(HOST, PORT, PROTOCOL)).setCompressionEnabled(true);CredentialsProvider credentialsProvider = new BasicCredentialsProvider();credentialsProvider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials(username, password));try {SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, TrustAllStrategy.INSTANCE).build();clientBuilder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setDefaultCredentialsProvider(credentialsProvider));} catch (Exception e) {log.error("EsClient_elasticsearchClient, init RestClient error. error msg:{}", e.getMessage());}return clientBuilder.build();}
}
3.5 发送请求给ES
写一个测试类来尝试操作ES:
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = GmallEsApplication.class)
@ContextConfiguration
public class EsClientTest{@Resourceprivate RestClient restClient;@Testpublic void performRequest() throws IOException {Request request = new Request("GET","/");Response response = restClient.performRequest(request);log.info("response:{}", JSON.toJSONString(response));if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {System.err.println("Method failed: " + response.getStatusLine());} else {HttpEntity entity = response.getEntity();String responseBody = EntityUtils.toString(entity);log.info("responseBody:{}", responseBody);}}}