
上篇学习了0基础学习Elasticsearch-Quick start,随后本篇研究如何使用Java操作ES
- 建议通篇阅读再回头来跟着敲代码
- 建议先阅读Java连接ES云以及如何使用CA证书连接、ES鉴权连接对Java连接ES有哪几种方法有个认知,阅读如何Reading responses,阅读如何同步、异步发送请求
- ES 8版本后建议使用
Java Low Level REST ClientJava客户端,本篇采用该客户端
<dependency>
<groupId>org.elasticsearch.clientgroupId>
<artifactId>elasticsearch-rest-clientartifactId>
<version>8.13.4version>
dependency>
low-level Java REST client内部采用了Apache Http Async Client来发送HTTP请求,内部含有以下这些依赖,如果遇到依赖冲突,需要解决:
如果遇到上面列出的依赖冲突,可以使用下面这个方法来解决,pom文件加入下面代码:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-shade-pluginartifactId>
<version>3.1.0version>
<executions>
<execution>
<phase>packagephase>
<goals><goal>shadegoal>goals>
<configuration>
<relocations>
<relocation>
<pattern>org.apache.httppattern>
<shadedPattern>hidden.org.apache.httpshadedPattern>
relocation>
<relocation>
<pattern>org.apache.loggingpattern>
<shadedPattern>hidden.org.apache.loggingshadedPattern>
relocation>
<relocation>
<pattern>org.apache.commons.codecpattern>
<shadedPattern>hidden.org.apache.commons.codecshadedPattern>
relocation>
<relocation>
<pattern>org.apache.commons.loggingpattern>
<shadedPattern>hidden.org.apache.commons.loggingshadedPattern>
relocation>
relocations>
configuration>
execution>
executions>
plugin>
plugins>
build>
概括:通过账号密码来获取连接。笔者这里通过注入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";
@Bean
public 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();
}
}
写一个测试类来尝试操作ES:
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = GmallEsApplication.class)
@ContextConfiguration
public class EsClientTest{
@Resource
private RestClient restClient;
@Test
public 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);
}
}
}