首页 > 编程语言 >elasticsearchjava客户端

elasticsearchjava客户端

时间:2024-01-23 16:44:22浏览次数:34  
标签:elasticsearchjava elasticSearchProperty return private client org import 客户端

elasticsearch java客户端

1.引用maven配置

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

2.定义elasticsearch的配置文件到springboot的application.properties

#dev
#config.es.address=127.0.0.1:9200

3.将application.properties配置文件中的配置抽取到配置文件解析类ElasticSearchProperty中

ElasticSearchProperty.java

@Data
@Configuration
@PropertySource(value = "classpath:config/application.properties")
@ConfigurationProperties(prefix = "config.es")
public class ElasticSearchProperty {

    /**
     * 连接地址,格式:IP:端口
     * 多个逗号分隔
     * 示例:127.0.0.1:9201,127.0.0.1:9202,127.0.0.1:9203
     */
    private String address="";

    /**
     * 用户名
     */
    private String userName;

    /**
     * 密码
     */
    private String password;

    /**
     * 连接超时时间
     * 默认10s
     */
    private int connectTimeout = 10000;

    /**
     * socket超时时间
     * 默认10s
     */
    private int socketTimeout = 60000;

    /**
     * 请求连接超时时间
     * 默认10s
     */
    private int connectionRequestTimeout = 10000;

    /**
     * 最大分页size
     * 默认10000
     */
    private int maxPageSize;
}

4.elasticsearch配置类中,加载es客户端

import net.bytebuddy.implementation.bytecode.Throw;
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.apache.logging.log4j.util.Strings;
import org.elasticsearch.client.Node;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * ElasticSearch Rest client 配置
 */
@Configuration
public class ElasticSearchConfig {
    private static final Logger log = LoggerFactory.getLogger(ElasticSearchConfig.class);


    @Resource
    private ElasticSearchProperty elasticSearchProperty;

    public ElasticSearchProperty getElasticSearchProperty() {
        return elasticSearchProperty;
    }

    public void setElasticSearchProperty(ElasticSearchProperty elasticSearchProperty) {
        this.elasticSearchProperty = elasticSearchProperty;
    }
    
    // 定义restClient生成的相关builder
    @Bean
    public RestClientBuilder restClientBuilder() {
        Assert.notNull(elasticSearchProperty, "elasticSearchProperty cannot null ");
        Assert.notNull(elasticSearchProperty.getAddress(), "address hosts  cannot null ");

        //ElasticSearch 连接地址地址
        HttpHost[] httpHosts = this.getElasticSearchHttpHosts();
        return RestClient.builder(httpHosts).setRequestConfigCallback(requestConfigBuilder -> {
            //设置连接超时时间
            requestConfigBuilder.setConnectTimeout(elasticSearchProperty.getConnectTimeout());
            requestConfigBuilder.setSocketTimeout(elasticSearchProperty.getSocketTimeout());
            requestConfigBuilder.setConnectionRequestTimeout(elasticSearchProperty.getConnectionRequestTimeout());
            return requestConfigBuilder;
        }).setHttpClientConfigCallback(httpClientBuilder -> {
            //Commented by Allen 启用Auth的话,此属性会导致认证不通过
            //httpClientBuilder.disableAuthCaching();
            //设置账密
            return getHttpAsyncClientBuilder(httpClientBuilder);
        });
    }
    /**
     * ElasticSearch Rest client 配置,单例client并引用上面定义的clientBuilder
     *
     * @return RestHighLevelClient
     */
    @Bean
    public RestHighLevelClient restHighLevelClient(@Qualifier("restClientBuilder") RestClientBuilder restClientBuilder) {
        return new RestHighLevelClient(restClientBuilder);
    }

    /**
     * ElasticSearch 连接地址
     * 多个逗号分隔,es都连接都连接
     * 示例:127.0.0.1:9201,127.0.0.1:9202,127.0.0.1:9203
     */
    private HttpHost[] getElasticSearchHttpHosts() {
        String[] hosts = elasticSearchProperty.getAddress().split(",");
        HttpHost[] httpHosts = new HttpHost[hosts.length];
        for (int i = 0; i < httpHosts.length; i++) {
            String host = hosts[i];
            host = host.replaceAll("http://", "").replaceAll("https://", "");
            Assert.isTrue(host.contains(":"), String.format("your host:[%s] format error , Please refer to [ 127.0.0.1:9200 ] ,", host));
            httpHosts[i] = new HttpHost(host.split(":")[0], Integer.parseInt(host.split(":")[1]), "http");
        }
        return httpHosts;
    }

    private HttpAsyncClientBuilder getHttpAsyncClientBuilder(HttpAsyncClientBuilder httpClientBuilder) {
        if (Strings.isBlank(elasticSearchProperty.getUserName()) || Strings.isBlank(elasticSearchProperty.getPassword())) {
            return httpClientBuilder;
        }
        //账密设置
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        //es账号密码(一般使用,用户elastic)
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(elasticSearchProperty.getUserName(), elasticSearchProperty.getPassword()));
        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        return httpClientBuilder;
    }
}

5.使用highLevelApi的client(ElasticSearchRestApiClient 引用了RestHighLevelClient)

ElasticSearchRestApiClient

@Slf4j
@Component
public class ElasticSearchRestApiClient {
    private static final String SEARCH_BY_AGG_UMPKEY = "delta.dao.es.searchByAgg";
    public static final String SCROLL_UMPKEY = "delta.dao.es.scroll";

    @Resource
    private ElasticSearchProperty elasticSearchProperty;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    public RestHighLevelClient getRestHighLevelClient() {
        return restHighLevelClient;
    }


    public AsyncSearchClient getAsyncClient() {
        return restHighLevelClient.asyncSearch();
    }

    public void setRestHighLevelClient(RestHighLevelClient restHighLevelClient) {
        this.restHighLevelClient = restHighLevelClient;

    }

    /**
     * 默认主分片数
     */
    private static final int DEFAULT_SHARDS = 5;
    /**
     * 默认副本分片数
     */
    private static final int DEFAULT_REPLICAS = 1;

    /**
     * 判断索引是否存在
     *
     * @param index 索引
     * @return 返回 true,表示存在
     */
    public boolean existsIndex(String index) throws ElasticSearchRuntimeException {
        try {
            GetIndexRequest request = new GetIndexRequest(index);
            request.local(false);
            request.humanReadable(true);
            request.includeDefaults(false);

            return restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("[ elasticsearch ] >> get index exists exception ,index:{} ", index, e);
            throw new ElasticSearchRuntimeException("[ elasticsearch ] >> get index exists exception:" + e.getMessage(), e);
        }
    }
}

标签:elasticsearchjava,elasticSearchProperty,return,private,client,org,import,客户端
From: https://www.cnblogs.com/PythonOrg/p/17982796

相关文章

  • 使用Go进行HTTP客户端认证
    在Go语言中,HTTP客户端认证可以通过net/http包来实现。下面是一个简单的示例,展示如何使用Go进行HTTP客户端认证。首先,确保你已经安装了Go语言环境,并设置好了相关的环境变量。Go语言中的HTTP客户端认证主要涉及到设置请求头中的认证信息。以下是一个简单的示例代码,展示了如何使用Go发......
  • k8s_client-go 构建客户端的几种方式
    kubernetesclient-go构建客户端的几种方式packagecallk8simport( "context" "log" metav1"k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" "k8s.io/client-go/t......
  • 比特币客户端&比特币回归测试网络
    比特币客户端&比特币回归测试网络实验概述区块链技术需要协调一个庞大的去中心化网络以实现功能复杂的分布式状态机副本,必然涉及频繁的指令交互。在此过程中,除了设计功能完备、高鲁棒性的客户端程序,作为构建和调试分布式系统的重要协议,RPC(远程过程调用)也是实现上述功能不可或缺......
  • 前端歌谣-第六十五课-express之服务端渲染和客户端渲染
    前言我是歌谣微信公众号关注前端小歌谣一起学习前端知识今天继续给大家讲解服务端渲染和客户端渲染静态资源的讲解案列index.html<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width,init......
  • HHDESK端口转发监控服务获取客户端和数据库之间的交互信息
    1.用户痛点端口转发是一种网络技术,用于将外部网络请求转发到内部网络中的特定设备或服务。它允许通过公共网络访问内部网络中的资源,提供了灵活性和便利性。传统的端口转发方式是通过配置路由器的端口映射,但这需要具备网络知识和一定的技术操作,对于一般用户来说较为繁琐。而HHDESK......
  • (七):ElasticSearch客户端操作
    ElasticSearch服务的客户端,有以下三种方式:·elasticsearch-head插件·elasticsearch提供的Restful接口直接访问·elasticsearch提供的API进行访问1、elasticsearch-head插件启动插件后,访问http://localhost:9100/地址,详情如下:1.1、概览信息概览信息......
  • RocketMQ消息客户端生产与消费的基本实现
    支撑环境JDK:javaversion"1.8.0_391"应用框架:org.springframework.boot:2.7.17RocketMQ客户端SDK:rocketmq-spring-boot-starter:2.2.3生产者消息提供者添加依赖implementation'org.apache.rocketmq:rocketmq-spring-boot-starter:2.2.3'添加配置application.......
  • RabbitMQ学习四 java客户端连接RabbitMQ
    RabbitMQ的工作模式,可以参考官网:https://www.rabbitmq.com/getstarted.html一、简单方式以下两种都是生产者直接发消息给队列,不通过交换机。且发送给队列的消息只能被消费一次。比如一个队列被C1和C2消费,在队列中的消息只会被一个消费者消费。生产者代码逻辑图代码如下:p......
  • 记录eletron客户端win7打包及安装使用问题
    win7nodeV14环境配置不能使用msi包安装nodeV14.x,需要下载zip包,手动解压安装文件。下载,nodeV14.15.3下载地址下载完成后解压,并配置环境变量系统变量新增 NODE_PATH 为 C:\nodepath-xx\node_modules系统变量新增 NODE_SKIP_PLATFORM_CHECK 为 1系统变量 path 追加 ;C:\node......
  • MFC---多线程(qq群聊的服务端和客户端)
    服务端//多线程+socket编程的一个联合使用//用互斥体进行线程同步socket编程临界区全局变量#include<WinSock2.h>#include<iostream>#include<windows.h>#include<process.h>#pragmacomment(lib,"ws2_32.lib")#defineMAX_CLNT256#defineMAX_BUF_S......