0基础学习Elasticsearch-使用Java操作ES

在这里插入图片描述

1 背景

上篇学习了0基础学习Elasticsearch-Quick start,随后本篇研究如何使用Java操作ES

2 前言

  1. 建议通篇阅读再回头来跟着敲代码
  2. 建议先阅读Java连接ES云以及如何使用CA证书连接ES鉴权连接对Java连接ES有哪几种方法有个认知,阅读如何Reading responses,阅读如何同步、异步发送请求
  3. ES 8版本后建议使用Java Low Level REST ClientJava客户端,本篇采用该客户端

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";
    @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();
    }
}

3.5 发送请求给ES

写一个测试类来尝试操作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);
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值