java 使用HighLevelRESTClient连接ES

1、引入jar包

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>6.4.3</version>
    <exclusions>
        <exclusion>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-client</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>6.4.3</version>
    <scope>compile</scope>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-client</artifactId>
    <version>6.4.3</version>
    <scope>compile</scope>
</dependency>

2、没有密码的连接方式

package com.example.shiro.db;


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.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;

public class EsClient {
    @Value("${es.http.server}")
    //可以是一组,多个以逗号分割
    private String httpServer;

    private RestHighLevelClient client;

    public RestHighLevelClient getInstance() {
        if (client == null) {
            synchronized (EsClient.class) {
                if (client == null) {
                    String[] nodes = httpServer.split(",");
                    HttpHost[] servers = new HttpHost[nodes.length];
                    for (int i = 0; i < nodes.length; i++) {
                        String[] node = nodes[i].split(":");
                        servers[i] = new HttpHost(node[0], Integer.parseInt(node[1]), "http");
                    }
                    client = new RestHighLevelClient(servers);
                }
            }
        }
        return client;
    }

    public void close() {
        try {
            if (client != null) {
                client.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3、需要密码的连接代码

package com.example.shiro.db;


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.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;

public class EsClient {
    @Value("${es.http.server}")
    //可以是一组,多个以逗号分割
    private String httpServer;

    @Value("${es.http.user}")
    //用户
    private String user;

    @Value("${es.http.pwd}")
    //密码
    private String pwd;

    private RestHighLevelClient client;

    public RestHighLevelClient getInstance() {
        if (client == null) {
            synchronized (EsClient.class) {
                if (client == null) {
                    String[] nodes = httpServer.split(",");
                    HttpHost[] servers = new HttpHost[nodes.length];
                    for (int i = 0; i < nodes.length; i++) {
                        String[] node = nodes[i].split(":");
                        servers[i] = new HttpHost(node[0], Integer.parseInt(node[1]), "http");
                    }
                    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pwd));
                    RestClientBuilder restClientBuilder = RestClient.builder(servers)
                            .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                                @Override
                                public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {
                                    return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                                }
                            });
                    client = new RestHighLevelClient(restClientBuilder);
                }
            }
        }
        return client;
    }

    public void close() {
        try {
            if (client != null) {
                client.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Elasticsearch的Java API连接Elasticsearch集群,需要添加以下三个依赖:org.elasticsearch.client.elasticsearch-rest-high-level-client、org.elasticsearch.client:elasticsearch-rest-client、org.elasticsearch:elasticsearch。这些依赖可以通过Maven或Gradle添加到项目中。接下来,可以使用Elasticsearch的Java API编写代码来连接Elasticsearch集群。具体步骤如下: 1. 创建RestHighLevelClient对象,该对象是与Elasticsearch集群进行通信的主要入口点。 2. 创建IndexRequest对象,该对象表示要索引的文档。 3. 使用IndexRequest对象设置索引名称、文档类型和文档ID等信息。 4. 使用IndexRequest对象设置要索引的文档内容。 5. 使用RestHighLevelClient对象执行IndexRequest对象,将文档索引到Elasticsearch集群中。 下面是一个示例代码,用于将文档索引到Elasticsearch集群中: ```java import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.IndexNotFoundException; import org.elasticsearch.rest.RestStatus; import java.io.IOException; public class ElasticsearchExample { private RestHighLevelClient client; public ElasticsearchExample(RestHighLevelClient client) { this.client = client; } public void indexDocument(String index, String type, String id, String json) throws IOException { IndexRequest request = new IndexRequest(index, type, id); request.source(json, XContentType.JSON); IndexResponse response = client.index(request, RequestOptions.DEFAULT); if (response.status() == RestStatus.CREATED) { System.out.println("Document indexed successfully"); } else { System.out.println("Failed to index document"); } } public static void main(String[] args) throws IOException { RestHighLevelClient client = new RestHighLevelClient(/* Elasticsearch连接配置 */); ElasticsearchExample example = new ElasticsearchExample(client); example.indexDocument("my_index", "my_type", "1", "{\"name\":\"John Doe\",\"age\":25}"); client.close(); } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值