SpringBoot -ElasticSearch RestHighLevelClient 高级客户端使用(1) 初始化

本文详细介绍了如何在SpringBoot环境中整合ElasticSearch6.4.2版本,包括配置依赖、创建配置文件及客户端工厂,以及如何在项目中注入并使用RestHighLevelClient。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

此处使用ElasticSearch6.4.2版本
SpringBoot 和ElasticSearch 环境以及 安装ik分词等操作不再缀诉,直接进入整合,本节不阐述原理

  1. 导入依赖
    此处使用的elasticsearch为6.4.2版本,SpringBoot 版本为2.0.6
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>6.4.2</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>6.4.2</version>
        </dependency>
  1. 创建配置文件
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

@Configuration
@ComponentScan(basePackageClasses=ESClientSpringFactory.class)
public class ESConfig {
    @Value("${elasticSearch.host}")
    private String host;

    @Value("${elasticSearch.port}")
    private int port;

    @Value("${elasticSearch.client.connectNum}")
    private Integer connectNum;

    @Value("${elasticSearch.client.connectPerRoute}")
    private Integer connectPerRoute;

    @Bean
    public HttpHost httpHost(){
        return new HttpHost(host,port,"http");
    }

    @Bean(initMethod="init",destroyMethod="close")
    public ESClientSpringFactory getFactory(){
        return ESClientSpringFactory.
                build(httpHost(), connectNum, connectPerRoute);
    }

    @Bean
    @Scope("singleton")
    public RestClient getRestClient(){
        return getFactory().getClient();
    }

    @Bean
    @Scope("singleton")
    public RestHighLevelClient getRHLClient(){
        return getFactory().getRhlClient();
    }

}
  1. 创建clientFactory
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;

import java.io.IOException;

public class ESClientSpringFactory {

    public static int CONNECT_TIMEOUT_MILLIS = 1000;
    public static int SOCKET_TIMEOUT_MILLIS = 30000;
    public static int CONNECTION_REQUEST_TIMEOUT_MILLIS = 500;
    public static int MAX_CONN_PER_ROUTE = 10;
    public static int MAX_CONN_TOTAL = 30;

    private static HttpHost HTTP_HOST;
    private RestClientBuilder builder;
    private RestClient restClient;
    private RestHighLevelClient restHighLevelClient;

    private static ESClientSpringFactory esClientSpringFactory = new ESClientSpringFactory();

    private ESClientSpringFactory(){}

    public static ESClientSpringFactory build(HttpHost httpHost,
                                              Integer maxConnectNum, Integer maxConnectPerRoute){
        HTTP_HOST = httpHost;
        MAX_CONN_TOTAL = maxConnectNum;
        MAX_CONN_PER_ROUTE = maxConnectPerRoute;
        return  esClientSpringFactory;
    }

    public static ESClientSpringFactory build(HttpHost httpHost,Integer connectTimeOut, Integer socketTimeOut,
                                              Integer connectionRequestTime,Integer maxConnectNum, Integer maxConnectPerRoute){
        HTTP_HOST = httpHost;
        CONNECT_TIMEOUT_MILLIS = connectTimeOut;
        SOCKET_TIMEOUT_MILLIS = socketTimeOut;
        CONNECTION_REQUEST_TIMEOUT_MILLIS = connectionRequestTime;
        MAX_CONN_TOTAL = maxConnectNum;
        MAX_CONN_PER_ROUTE = maxConnectPerRoute;
        return  esClientSpringFactory;
    }


    public void init(){
        builder = RestClient.builder(HTTP_HOST);
        setConnectTimeOutConfig();
        setMutiConnectConfig();
        restClient = builder.build();
        restHighLevelClient = new RestHighLevelClient(builder);
        System.out.println("init factory");
    }
    // 配置连接时间延时
    public void setConnectTimeOutConfig(){
        builder.setRequestConfigCallback(requestConfigBuilder -> {
            requestConfigBuilder.setConnectTimeout(CONNECT_TIMEOUT_MILLIS);
            requestConfigBuilder.setSocketTimeout(SOCKET_TIMEOUT_MILLIS);
            requestConfigBuilder.setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT_MILLIS);
            return requestConfigBuilder;
        });
    }
    // 使用异步httpclient时设置并发连接数
    public void setMutiConnectConfig(){
        builder.setHttpClientConfigCallback(httpClientBuilder -> {
            httpClientBuilder.setMaxConnTotal(MAX_CONN_TOTAL);
            httpClientBuilder.setMaxConnPerRoute(MAX_CONN_PER_ROUTE);
            return httpClientBuilder;
        });
    }

    public RestClient getClient(){
        return restClient;
    }

    public RestHighLevelClient getRhlClient(){
        return restHighLevelClient;
    }

    public void close() {
        if (restClient != null) {
            try {
                restClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("close client");
    }
}
  1. 添加配置,在application.properties里添加以下内容
elasticSearch.host=172.17.0.1
elasticSearch.port=9200
elasticSearch.client.connectNum=10
elasticSearch.client.connectPerRoute=50

至此整合完成
启动后RestHighLevelClient 处于可用状态
使用

@Autowired
private RestHighLevelClient rhlClient;

即可调用RestHighLevelClient

### Spring Boot 中 RestHighLevelClient 多节点连接并带有账户密码的初始化配置示例 在 Spring Boot 项目中,可以通过配置 `RestHighLevelClient` 来实现多节点连接,并设置账户和密码进行身份验证。以下是详细的配置方法[^2]: #### 1. 添加依赖 确保项目中包含以下 Maven 依赖以支持 Elasticsearch 客户端和 HTTP 请求功能[^2]: ```xml <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.10.2</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> ``` #### 2. 配置 RestHighLevelClient 通过 Spring Boot 的配置类来初始化 `RestHighLevelClient`,并设置多节点地址及认证信息。 ```java 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.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.io.IOException; @Configuration public class ElasticsearchConfig { @Bean(destroyMethod = "close") public RestHighLevelClient restHighLevelClient() { // 定义多个节点地址 HttpHost[] httpHosts = new HttpHost[]{ new HttpHost("node1.example.com", 9200, "http"), new HttpHost("node2.example.com", 9200, "http"), new HttpHost("node3.example.com", 9200, "http") }; // 配置用户名和密码 final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "your_password")); // 创建 RestHighLevelClient 实例 return new RestHighLevelClient( RestClient.builder(httpHosts) .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider))); } } ``` #### 3. 配置说明 - **多节点支持**:通过 `HttpHost` 数组传递多个节点地址,确保高可用性和负载均衡[^2]。 - **身份验证**:使用 `BasicCredentialsProvider` 设置用户名和密码,适用于需要身份验证的集群环境[^2]。 - **自动关闭资源**:通过 `@Bean(destroyMethod = "close")` 确保在应用关闭时释放客户端资源。 #### 4. 使用 RestHighLevelClient 在其他服务类中注入 `RestHighLevelClient` 并使用它执行操作,例如索引文档或查询数据。 ```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.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.IOException; @Service public class ElasticsearchService { @Autowired private RestHighLevelClient restHighLevelClient; public void indexDocument(String indexName, String id, String jsonString) throws IOException { IndexRequest request = new IndexRequest(indexName).id(id).source(jsonString); IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT); System.out.println("Indexed document: " + response.getId()); } } ``` --- ###
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值