Elasticsearch 8.x 单机/集群安装配置,SpringBoot整合,Kibana集成应用示例

Spring Boot2.1.x整合Elasticsearch8.x 阅读详情
AI摘要

本文介绍了Elasticsearch 8.x的单机和集群安装配置,包括下载、用户配置、服务配置等。还讲述了Kibana的安装与配置,以及IK分词器的安装。同时,详细说明了Elasticsearch与SpringBoot的整合步骤,如获取证书、配置依赖等,为相关开发提供了实用示例。

系统环境

OS:centos7

安装Elasticsearch

下载

https://www.elastic.co/cn/downloads/elasticsearch
此处下载版本8.2.2
ES 8.x版本内置jdk,不依赖JAVA环境变量,如果需要使用本地JAVA环境可以定义ES_JAVA_HOME变量或者在ES安装目录下bin/elasticsearch-env文件中指定。,不过需要1.8及以上的JDK。

安装配置

解压缩并copy到/user/local目录

 1. tar -xzvf elasticsearch-8.2.2
 2. mv elasticsearch-8.2.2 /usr/local/

编辑config/elasticsearch.yml文件,放开network.host并修改为0.0.0.0,确保在服务启动之后可在其他主机访问ES服务。

配置用户

Elasticsearch服务不能以系统root用户身份启动,需要配置其他用户

groupadd esuser
useradd -g esuser esuser
chown -R esuser:esuser /usr/local/elasticsearch-8.2.2/

服务配置

此时如启动服务,将会报如下三个错误信息:

ERROR: [3] bootstrap checks failed. You must address the points described in the following [3] lines before starting Elasticsearch.
bootstrap check failure [1] of [3]: max file descriptors [4096] for elasticsearch process is too low, increase to at least [65535]
bootstrap check failure [2] of [3]: max number of threads [3818] for user [esuser] is too low, increase to at least [4096]
bootstrap check failure [3] of [3]: max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144]
ERROR: Elasticsearch did not exit normally - check the logs at /usr/local/elasticsearch-8.2.2/logs/elasticsearch.log

解决以上的启动异常,调整如下系统配置:

  1. ElasticSearch进程的最大文件描述大小至少需65535,修改配置文件 /etc/security/limits.conf,添加如下内容:
* soft nofile 65535
* hard nofile 65535
  1. 最大线程数至少需要4096,在刚才的配置文件刚才的位置添加如下内容:
* soft nproc 4096
* hard nproc 4096

针对1,2的以上配要生效的话也许需要用户重新登录或重启系统。

  1. 系统虚拟内存默认最大映射数至少262144,修改配置文件 /etc/sysctl.conf,在文件末尾添加(或修改)如下内容:
vm.max_map_count=262144

执行如下命令使其生效

sysctl -p

继续编辑配置文件 config/elasticsearch.yml,添加如下内容

ingest.geoip.downloader.enabled: false

否则,启动服务时报如下错误信息:

[2022-09-30T16:45:13,884][ERROR][o.e.i.g.GeoIpDownloader  ] [localhost.localdomain] exception during geoip databases update
java.net.SocketTimeoutException: Connect timed out
	at sun.nio.ch.NioSocketImpl.timedFinishConnect(NioSocketImpl.java:543) ~[?:?]

ES试图更新地图数据库,目前可以先禁掉,用时再说。

启动服务(切换至/bin目录),先使用如下命令看服务是否正常启动

./elasticsearch

一般情况,需要Elasticsearch在后台运行,执行如下命令

./elasticsearch -d

启动服务成功,控制台中显示了一些重要信息:

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✅ Elasticsearch security features have been automatically configured!
✅ Authentication is enabled and cluster connections are encrypted.

ℹ️  Password for the elastic user (reset with `bin/elasticsearch-reset-password -u elastic`):
  5m7XIY7EcopbKqdruXT2

ℹ️  HTTP CA certificate SHA-256 fingerprint:
  9b6d95393b9f5d4c598f5b91df0adcccb7afd9dec4177a4decc6db0268afec35

ℹ️  Configure Kibana to use this cluster:
• Run Kibana and click the configuration link in the terminal when Kibana starts.
• Copy the following enrollment token and paste it into Kibana in your browser (valid for the next 30 minutes):
  eyJ2ZXIiOiI4LjIuMiIsImFkciI6WyIxOTIuMTY4LjE3NC4xMDI6OTIwMCJdLCJmZ3IiOiI5YjZkOTUzOTNiOWY1ZDRjNTk4ZjViOTFkZjBhZGNjY2I3YWZkOWRlYzQxNzdhNGRlY2M2ZGIwMjY4YWZlYzM1Iiwia2V5IjoiZVBtTG5vTUJxYnlLQV91QlNZcVE6ekVhZS1wdzdSOS1yekgxVG1FeTV3USJ9

ℹ️ Configure other nodes to join this cluster:
• Copy the following enrollment token and start new Elasticsearch nodes with `bin/elasticsearch --enrollment-token <token>` (valid for the next 30 minutes):
  eyJ2ZXIiOiI4LjIuMiIsImFkciI6WyIxOTIuMTY4LjE3NC4xMDI6OTIwMCJdLCJmZ3IiOiI5YjZkOTUzOTNiOWY1ZDRjNTk4ZjViOTFkZjBhZGNjY2I3YWZkOWRlYzQxNzdhNGRlY2M2ZGIwMjY4YWZlYzM1Iiwia2V5IjoiZHZtTG5vTUJxYnlLQV91QlNZcDg6ZTJHUVlhY2FUaC1nYl9tblpQTVJvdyJ9

  If you're running in Docker, copy the enrollment token and run:
  `docker run -e "ENROLLMENT_TOKEN=<token>" docker.elastic.co/elasticsearch/elasticsearch:8.2.2`
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

把这些信息保存起来,远程登录或Kibana配置时需要用到,不过,到时候可以重置获取。

登录远程服务

有防火墙的话,首先开放9200端口:

firewall-cmd --zone=public --add-port=9200/tcp --permanent
firewall-cmd --reload

访问如下url:
https://ip:9200/ (注:是https,不是http)
要求输入用户名密码(前面保存的初次启动时显示的配置信息:elastic/)

可以运行如下命令来手动设置各用户的密码

./bin/elasticsearch-setup-passwords interactive

或者设置指定用户的密码

./bin/elasticsearch-reset-password --username elastic -i

登录后显示如下信息,说明系统成功启动并可访问

{
  "name" : "localhost.localdomain",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "uPCMas0jQ9mC7s4gU8pdng",
  "version" : {
    "number" : "8.2.2",
    "build_flavor" : "default",
    "build_type" : "tar",
    "build_hash" : "9876968ef3c745186b94fdabd4483e01499224ef",
    "build_date" : "2022-05-25T15:47:06.259735307Z",
    "build_snapshot" : false,
    "lucene_version" : "9.1.0",
    "minimum_wire_compatibility_version" : "7.17.0",
    "minimum_index_compatibility_version" : "7.0.0"
  },
  "tagline" : "You Know, for Search"
}

此处进一步探讨一个问题,学习时,在本地单机测试环境可能并不需要https、用户名密码、集群间身份验证,各种证书,令牌等,而只通过访问http://ip:9200的方式访问。

可以调整一下配置,修改配置文件config/elasticsearch.yml,找到如下信息内容(这部分信息是刚才启动时,基于https由es自动添加进来的)
在这里插入图片描述
把那4个true,改为false即可,访问http://ip:9200 ,就可以直接访问了,至此,从开发的角度已经可以使用了

安装配置Kibana

Kibana是一个开源的分析与可视化平台,用于和ES一起使用的。可以用kibana搜索、查看ES中的数据。Kibana以图表、表格、地图等,直观的展示ES中的数据。

下载

https://www.elastic.co/cn/downloads/kibana
注意与elasticsearch的版本匹配。

安装

解压缩并copy到/user/local目录

基本配置

修改配置文件:config/kibana.yml

  1. 服务端口
    server.port默认是5601
  2. 允许远程访问的地址
    server.host默认为本机,如果允许Kibana服务供远程主机访问,需要在这个配置中填写远程主机的ip地址,如果不限远程主机,改为:0.0.0.0

启动

./bin/kibana

启动kibana服务,不允许root用户启动(记得6.x的时候是可以的),可以改用上文中的esuser用户启动(需首先修改esuser对kibana目录及文件的权限),或者携带启动参数 --allow-root 使用root用户启动
在这里插入图片描述
根据url访问kibana服务(当然ip地址不是0.0.0.0),按照提示完成对于elasticsearch的配置即可

首先输入elastic启动中的令牌(token),如果token没有记下来或者已经失效,可以用这个命令重新获取

./bin/elasticsearch-create-enrollment-token --scope kibana

注意:登录时使用的用户是elastic

OK!!!现在可以对ES的索引库进行一些实操训练了
在这里插入图片描述

安装配置分词器(IK)

Elasticsearch默认分词器不支持中文,此处安装一个常用的IK分词器。
分词类型(下文应用中指定示例)
ik_max_word 对文本做最细 力度的拆分
ik_smart 对文本做最粗粒度的拆分,这个其实基本够用

  1. 下载
    https://github.com/medcl/elasticsearch-analysis-ik/releases
    注意与elasticsearch的版本匹配。
  2. 在easticsearch的plugins目录下创建名为 analyser_ik 的目录,将下载好的zip包解压在该目录下。
  3. 执行elasticsearch-plugin list 即可查看到该插件,重启elasticsearch服务。

在kibana终端查看分词效果:

GET _analyze
{
  "analyzer": "ik_smart",
  "text": "测试一下搜索苹果手机怎么样呢"
}

基本应用

考虑一个基本场景,也是目前很多电商平台的基本应用场景,用户在平台输入关键词搜索商品,系统展示匹配的商品列表,如果依靠RDBMS来实现,即便很多RDBMS提供了全文检索功能,但实现时还是比较吃力,对于数据库的压力当然也很大,这时ES作为搜索引擎就可以发挥它的优势(此处只是几个简单的示例)。

以下操作在kibana中完成

索引库管理

查询索引库列表

GET /_cat/indices?v

创建索引

PUT /index_product
{
  "mappings": {
    "properties": {
      "sname":{
        "type": "text",
        "analyzer": "ik_smart"
      },
      "surl":{
        "type": "keyword",
        "index": "false"
      },
      "price":{
        "type": "float",
        "index": "false"
      },
      "count":{
        "type": "integer",
        "index": "false"
      },
      "sdesc":{
        "type": "text",
        "analyzer": "ik_smart"
      },
      "ddate":{
        "type": "date",
        "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"
      }
    }
  }
}

mapping是对索引库中文档的约束,常见的mapping属性包括:

  • type:字段数据类型,常见的简单类型有:
    字符串:text(分词匹配),keyword(精确匹配,例如:品牌、国家、ip地址、email等)
    数值:long、integer、short、byte、double、float
    布尔:boolean
    日期:date
    对象:object
  • index:是否创建索引并参与搜索,默认为true
  • analyzer:使用哪种分词器
  • properties:该字段的子字段

查看索引

GET /index_product

修改索引

索引库一旦创建,无法修改mapping中已有的字段,但是却允许添加新的字段到mapping中,因为不会对倒排索引产生影响,这种方式相当于创建索引时不定义mapping,之后单独定义mapping。

PUT /index_product/_mapping
{
  "properties": {
    "sname":{
      "type": "text",
      "analyzer": "ik_smart"
    },
    "surl":{
      "type": "keyword",
      "index": "false"
    },
    "price":{
      "type": "float",
      "index": "false"
    },
    "count":{
      "type": "integer",
      "index": "false"
    },
    "sdesc":{
      "type": "text",
      "analyzer": "ik_smart"
    }
  }
}

查看映射

GET /index_product/_mapping

删除索引

DELETE /index_product

文档管理

创建文档

POST /index_product/_doc/product_1
{
    "sname": "烟台苹果水果",
    "surl": "http://product1.jpg",
    "price": "10.0",
    "count": "10",
    "sdesc": "山东烟台苹果,产地:烟台,山东特产"
}

多创建几个不同的DOC文档

查询文档

GET /index_product/_doc/product_1

GET /index_product/_search?q=sname:水果

POST index_product/_search
{
    "query": {
        "match_all": {}
    }
}

POST /index_product/_search
{
  "query": {
      "match": {
          "sdesc": "随便搜索北京特产"
      }
  }
}

POST /index_product/_search
{
  "query": {
    "multi_match": {
      "query": "水果",
      "fields": ["sname","sdesc"]
    }
  }
}

以上是几种不同的查询方式,查询结果表明,分词搜索已经生效,万里长征第一步。

修改文档

修改文档分为:全量修改、增量修改
全量修改与新增文档相同,只是ES内部实现逻辑的问题;
增量修改即改变文档的部分字段值,DSL如下:

POST /index_product/_update/product_2
{
  "doc": {
    "sname": "莱阳梨水果",
    "sdesc": "山东莱阳梨,产地:莱阳,山东特产"
  }
}

删除文档

DELETE /index_product/_doc/product_2

至此,已经完成了ES单机应用的服务配置,下面我们看一下ES集群的配置

Elasticsearch集群配置

此处使用三台服务器配置ES集群,建议根据上文的配置步骤重新配置安装Elasticsearch,基本配置完成后先不要运行,继续完成集群配置。
以下的集群配置可在其中一台服务器上进行(在elasticsearch目录先以esuser用户执行命令),配置完成之后copy到其他服务器即可。

生成ca证书:

./bin/elasticsearch-certutil ca

默认ca文件名为elastic-stack-ca.p12即可,设置ca密码12345678;

生成节点通信证书

./bin/elasticsearch-certutil cert --ca elastic-stack-ca.p12

要求输入ca证书密码,证书文件名默认为elastic-certificates.p12即可,两次输入通信证书密码12345678(可以与ca证书密码不同);

此两个证书文件将生成到当前目录下,copy到config/certs目录下。

设置节点通信密码

./bin/elasticsearch-keystore add xpack.security.transport.ssl.keystore.secure_password
./bin/elasticsearch-keystore add xpack.security.transport.ssl.truststore.secure_password

通信证书密码设置为12345678,与之前的证书密码保持一致,此时将在config目录下生成elasticsearch-keystore文件。

# 查看keystore中的信息
./bin/elasticsearch-keystore list

签发https证书

./bin/elasticsearch-certutil http

这个操作的步骤好像有点多,不过注意几个关键环节,其他可以直接取默认值回车或视情况输入n跳过即可

  1. 输入certs/elastic-stack-ca.p12的路径
  2. 输入三个节点的hostname
  3. 输入三个节点的ip地址
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
命令执行成功在es主目录下生成elasticsearch-ssl-http.zip压缩文件,解压缩找到elasticsearch目录下的 http.p12文件,copy到certs目录下,另外还有kibana目录下有一个配置文件elasticsearch-ca.pem,copy到kibana/confiig目录下。

将刚才配置的私钥的密码添加到 es中的安全设置中

./bin/elasticsearch-keystore add xpack.security.http.ssl.keystore.secure_password
./bin/elasticsearch-keystore add xpack.security.http.ssl.truststore.secure_password

配置elasticsearch.yml

修改配置文件Elasticsearch.yml中如下配置信息:

cluster.name: my-application #集群名称
node.name: node-1 #节点名称
node.roles: [master,data] # master选举资格(至少两个)
network.host: 0.0.0.0#允许连接IP
http.port: 9200 # 访问端口
http.cors.enabled: true #是否支持跨域,默认为false
http.cors.allow-origin: “*” #当设置允许跨域,默认为 *,支持所有域名
discovery.seed_hosts: [“192.168.174.101:9300”, “192.168.174.102:9300”,“192.168.174.103:9300”] #集群成员
cluster.initial_master_nodes: [“node-1”, “node-2”, “node-3”]

配置文件中添加如下证书配置信息:

xpack.security.enabled: true
xpack.security.enrollment.enabled: true
xpack.security.http.ssl:
  enabled: true
  keystore.path: certs/http.p12
  truststore.path: certs/http.p12
xpack.security.transport.ssl:
  enabled: true
  verification_mode: certificate
  keystore.path: certs/elastic-certificates.p12
  truststore.path: certs/elastic-certificates.p12

配置其他节点

拷贝

  1. elasticsearch-yml文件
  2. elasticsearch-keystore文件
  3. certs目录

到其他节点服务器相应位置(注意文件权限属性的调整),并修改elasticsearch.yml中节点名称。

如果一切正常,此时集群即配置完成。

启动集群

启动各节点elasticsearch服务,成功后,执行如下命令设置节点登录密码:

./bin/elasticsearch-reset-password --username elastic -i

配置Kibana

kibana不能使用elastic用户访问elastic服务,需要在elastic中为kibana用户设置密码,输入或由系统生成。

./bin/elasticsearch-reset-password -u kibana -i

在elastic中为kibana生成证书

./bin/elasticsearch-certutil csr -name kibana

此命令在ES目录下生成文件:csr-bundle.zip,解压缩后找到这两个文件:kibana.csr,kibana.key,移至kibana/config目录下,并在目录下执行下面的命令生成文件认证文件kibana.crt。:

openssl x509 -req -in kibana.csr -signkey kibana.key -out kibana.crt

配置kibana.yml,内容如下(下面的配置项在配置文件中都有,找到直接编辑):

server.ssl.enabled: true
server.ssl.certificate: config/kibana.crt
server.ssl.key: config/kibana.key

elasticsearch.hosts: ["https://192.168.174.101:9200"]

elasticsearch.username: "kibana" #es中创建的用户名
elasticsearch.password: "kibana" #用户密码

elasticsearch.ssl.certificateAuthorities: [ "config/elasticsearch-ca.pem" ] #https自签证书时生成的文件,也拷贝至此

到这儿,kibana针对es集群也配置完成,启动服务访问
https://ip:5601 试试吧,注意访问Kibana服务时的登录用户是elastic用户,而不是上面创建的kibana用户。

整合SpringBoot

获取证书和私钥

在config/certs目录下执行如下命令,从elastic-stack-ca.p12证书中获取crt证书,这是整合SpringBoot时需要用到的,elastic-stack-ca.p12是前面配置集群时生成的CA证书。

openssl pkcs12 -in elastic-stack-ca.p12 -nokeys -out ca.crt

从elastic-stack-ca.p12证书中获取key私钥(整合时不需要,仅在此记录)

openssl pkcs12 -in elastic-stack-ca.p12 -nocerts -nodes -out ca.key

在SpringBoot项目resource下创建certs目录,把cat.crt证书copy至此

maven依赖配置

从ES 7.15.0 开始官方已弃用elasticsearch-rest-high-level-client,因此不推荐使用 REST 客户端;
考虑到ES的版本升级太快,也不推荐spring-boot-starter-data-elasticsearch,它的更新速度完全跟不上ES的版本迭代速度,而且对于ES的高级特性支持也不友好;
ES官方推荐使用 Elasticsearch Java API客户端

一下是pom.xml配置中需要添加的依赖(非全部)

	<repositories>
        <!-- add the elasticsearch repo -->
        <repository>
            <id>elasticsearch-releases</id>
            <url>https://artifacts.elastic.co/maven</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
    
	<dependencies>
		<dependency>
	        <groupId>com.fasterxml.jackson.core</groupId>
	        <artifactId>jackson-databind</artifactId>
		</dependency>
		<dependency>
	        <groupId>org.glassfish</groupId>
	        <artifactId>jakarta.json</artifactId>
	        <version>2.0.1</version>
		</dependency>
		<dependency>
	        <groupId>co.elastic.clients</groupId>
	        <artifactId>elasticsearch-java</artifactId>
	        <version>8.2.2</version>
		</dependency>
	</dependencies>

配置文件application.yml

在配置文件中添加如下内容

elasticsearch:
  hosts: 192.168.174.101:9200,192.168.174.102:9200
  username: elastic
  password: elastic

JAVA配置类

import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;

import javax.net.ssl.SSLContext;

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.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder.HttpClientConfigCallback;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StringUtils;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.indices.GetIndexResponse;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import lombok.extern.slf4j.Slf4j;

@Configuration
@Slf4j
public class ElasticsearchConfig {
    @Value("${elasticsearch.hosts}")
	private String hosts;
    @Value("${elasticsearch.username}")
    private String username;
    @Value("${elasticsearch.password}")
    private String password;

    @Bean
    public ElasticsearchClient ESClient() throws Exception {
        ElasticsearchTransport transport = getElasticsearchTransport(username, password, getHosts());
        return new ElasticsearchClient(transport);
    }

    /**
     * 解析hosts字符串,转为HttpHost对象数组
     */
    private HttpHost[] getHosts() {
        if (!StringUtils.hasLength(hosts)) {
            throw new RuntimeException("invalid elasticsearch configuration");
        }

        String[] hostArray = hosts.split(",");
        HttpHost[] httpHosts = new HttpHost[hostArray.length];
        HttpHost httpHost;
        for (int i = 0; i < hostArray.length; i++) {
            String[] strings = hostArray[i].split(":");
            httpHost = new HttpHost(strings[0], Integer.parseInt(strings[1]), "https");
            httpHosts[i] = httpHost;
        }

        return httpHosts;
    }

    private static SSLContext buildSSLContext() {
        ClassPathResource resource = new ClassPathResource("certs/ca.crt");
        SSLContext sslContext = null;
        try {
            CertificateFactory factory = CertificateFactory.getInstance("X.509");
            Certificate trustedca;
            try (InputStream is = resource.getInputStream()) {
                trustedca = factory.generateCertificate(is);
            }
            KeyStore trustStore = KeyStore.getInstance("pkcs12");
            trustStore.load(null, null);
            trustStore.setCertificateEntry("ca", trustedca);
            SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null);
            sslContext = sslContextBuilder.build();
        } catch (CertificateException | IOException | KeyStoreException | NoSuchAlgorithmException | KeyManagementException e) {
            log.error("elasticsearch认证失败", e);
        }

        return sslContext;
    }

    private static ElasticsearchTransport getElasticsearchTransport(String username, String passwd, HttpHost...hosts) {
        //配置账号密码
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, passwd));

        //设置自签证书
        HttpClientConfigCallback callback = httpAsyncClientBuilder -> httpAsyncClientBuilder
                .setSSLContext(buildSSLContext())
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .setDefaultCredentialsProvider(credentialsProvider);

        //创建RestClient
        RestClient client = RestClient
                           .builder(hosts)
                           .setHttpClientConfigCallback(callback)
                           .build();

        return new RestClientTransport(client, new JacksonJsonpMapper());
    }
}

到这儿,其实后面的内容已经不关键了,具体对ES的操作网上一搜一堆,但是,针对ES8的集群与SpringBoot的整合,因为模拟生产环境,涉及SSL证书等,反而比较少,配置到这儿关键问题已经基本解决。
如果感兴趣可以继续往下看,只是一点ES应用的皮毛,更高级的应用再继续搜索学习吧

doc映射类

此处使用上文用到的product

import java.util.Date;

public class Product {
	String uid;
	String sname;
	int count;
	double price;
	String surl;
	String sdesc;
	Date ddate;

	public Product() {
		
	}
	
	public Product(String uid, String sname, int count, double price, String surl, String sdesc) {
		super();
		this.uid = uid;
		this.sname = sname;
		this.count = count;
		this.price = price;
		this.surl = surl;
		this.sdesc = sdesc;
	}
	
	public String getUid() {
		return uid;
	}

	public void setUid(String uid) {
		this.uid = uid;
	}

	public String getSname() {
		return sname;
	}
	
	public void setSname(String sname) {
		this.sname = sname;
	}
	
	public int getCount() {
		return count;
	}
	
	public void setCount(int count) {
		this.count = count;
	}
	
	public double getPrice() {
		return price;
	}
	
	public void setPrice(double price) {
		this.price = price;
	}
	
	public String getSurl() {
		return surl;
	}
	
	public void setSurl(String surl) {
		this.surl = surl;
	}
	
	public String getSdesc() {
		return sdesc;
	}
	
	public void setSdesc(String sdesc) {
		this.sdesc = sdesc;
	}
	
	public Date getDdate() {
		return ddate;
	}

	public void setDdate(Date ddate) {
		this.ddate = ddate;
	}
}

服务类

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.IndexRequest;
import co.elastic.clients.elasticsearch.core.IndexResponse;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
import co.elastic.clients.elasticsearch.indices.GetIndexResponse;

import org.springframework.stereotype.Service;

import com.skt.bus.es.dto.Product;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@Service
public class ESService {

    @Resource(name="ESClient")
    private ElasticsearchClient elasticsearchClient;

    //创建索引
    public void addIndex(String name) throws IOException {
        elasticsearchClient.indices().create(c -> c.index(name));
    }
    
    //判断索引是否存在
    public boolean indexExists(String name) throws IOException {
        return elasticsearchClient.indices().exists(b -> b.index(name)).value();
    }

    //删除索引
    public void delIndex(String name) throws IOException {
        elasticsearchClient.indices().delete(d -> d.index(name));
    }
    
    //查询索引
    public void searchIndex(String name) throws IOException {
    	GetIndexResponse res = elasticsearchClient.indices().get(e -> e.index(name));
    	System.out.println(res.result());
    }
    
    //创建product doc
    public void addIndex(Product product) throws IOException {
    	//method 1
    	IndexRequest<Object> indexRequest = new IndexRequest.Builder<>()
                .index("index_product")
                .id(product.getUid())
                .document(product)
                .build();
     	elasticsearchClient.index(indexRequest);
 
     	//method 2
    	elasticsearchClient.index(builder -> builder
                .index("index_product")
                .id(product.getUid())
                .document(product)
        );
    }

    //模糊搜索product doc
    public void searchMultiMatch(String key) throws IOException {
    	SearchResponse<Product> r = elasticsearchClient.search(s -> s
        	.index("index_product")
        	.query(q -> q
        		.multiMatch(m -> m
                	.query(key)
                	.fields("sname","sdesc")
        		)
            ),
        	Product.class
    	);
    	List<Hit<Product>> hits = r.hits().hits();
    	for (Hit<Product> hit: hits) {
            Product product2 = hit.source();
            System.out.println("product " + product2.getUid() + ", score " + hit.score());
        }
    }
}

SpringBoot测试类

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import com.skt.bus.es.dto.Product;
import com.skt.bus.es.service.ESService;

@SpringBootTest
class TstsocketApplicationTests {
    @Autowired
    ESService esService;

	@Test
	void contextLoads() throws Exception {
		try {
		esService.searchMultiMatch("特产");
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	void addProduct() throws Exception {
		Product p = new Product();
		p.setUid("pid");
		p.setCount(11);
		p.setPrice(11.11);
		p.setSurl("kaoya.jpb");
		p.setSname("全聚德烤鸭");
		p.setSdesc("北京特产,烤鸭,全聚德");
		
		esService.addIndex(p);
	}
	
    void addIndex() throws Exception {
        String indexName = "index_test";
        try {
	        Assertions.assertFalse(esService.indexExists(indexName));
	        esService.addIndex(indexName);
	        Assertions.assertTrue(esService.indexExists(indexName));
	        esService.delIndex(indexName);
	        Assertions.assertFalse(esService.indexExists(indexName));
        }
        catch (Exception e) {
        	e.printStackTrace();
        }
    }
}

到此为止,本文对于ES 8.x的单机环境配置应用,集群配置应用,SpringBoot集成,Kibana配置应用做了一个简单的示例,同时也作为个人记录备查,希望能对有需要的同学有点帮助。

在此多谢网上各位大侠的帖文,一边学习一边根据本人对特定业务场景进行应用分析,文中内容如有冒犯之处,请指出,本人加以更改;另外,文中如有错漏之处,还请各位大侠指正,谢谢!

如转载请注明出处!

Elasticsearch8搭建及Springboot中集成使用 Elasticsearch8搭建及Springboot中集成使用 1.搭建;2.springboot中集成配置,基础框架结构,通用方法及业务示例。 阅读详情

相关推荐

【ElasticSearch8】SpringBoot集成ElasticSearch8.x 基本应用 CRUD操作 环境安装

前言 最近在研究es的时候发现官方已经在7.15.0放弃对旧版本中的Java REST Client (High Level Rest Client (HLRC))的支持,从而替换为推荐使用的Java API Client 8.x 查看SpringBoot2.6.4的依赖,其中es的版本仅为7.15.2 <dependency> <groupId>org.springframework.boot</groupId> <

Sidney_Jack_1101的博客 2万+

SpringBoot3整合Elasticsearch8.x之全面保姆级教程

SpringBoot3整合Elasticsearch8.x之全面保姆级教程,非常全面

热爱编程的你我 1万+

Java企业级电商项目实战:SpringBoot整合Redis、RabbitMQ、Elasticsearch

在分布式系统架构中,缓存、消息队列和搜索引擎是提升应用性能与可扩展性的核心技术组件。缓存技术通过将热点数据存储在内存中,有效降低数据库访问压力,其核心原理是利用内存的高速读写特性。消息队列基于生产者-消费者模型,实现系统间的异步解耦与流量削峰,保障关键业务流程的可靠性。搜索引擎则通过倒排索引等机制,为海量数据提供高效的全文检索能力。这些技术的工程价值在于,它们共同构建了高并发、高可用的现代互联网应用基础架构。在电商、社交、内容平台等典型应用场景中,它们分别解决了会话管理、商品详情缓存、异步订单处理与商品搜索

weixin_34232744的博客 379

Elasticsearch8版本安装详解,单节点部署、多节点部署、冷热温集群部署、IK分词器安装、简单生产安全模式配置

Elasticsearch8版本安装详解,单节点部署、多节点部署、冷热温集群部署、IK分词器安装、简单生产安全模式配置,配置文件参数基础

timber wolf 1万+

CentOS 7 + InfluxDB + collectd 构建轻量级系统指标监控体系

时间序列数据库是存储和分析带时间戳的数值型监控数据(如CPU、内存、磁盘IO)的核心基础设施。InfluxDB凭借专为时序优化的TSM引擎、高压缩率与原生降采样能力,显著优于MySQL或Elasticsearch等通用数据库在system metrics场景下的表现;结合资源占用极低、内核兼容性久经验证的collectd,在CentOS 7 minimal环境下可实现稳定高效的指标采集。该组合无需容器编排或云服务依赖,适用于物理机、VMware虚拟机及边缘服务器等受限环境,广泛应用于运维可观测性建设、性能压

diaoqu4574的博客 404

Java后端开发从入门到进阶整体专栏目录汇总

本文是「Java后端开发从入门到进阶」付费专栏的整体目录汇总,按入门、应用、进阶三层与七个阶段规划学习路线,覆盖基础内功、数据库缓存、工程化、主流框架、分布式微服务、运维排查与源码架构设计。

每个人都是独一无二的,把握好自己的节奏,跟着自己的心走。 1028

【elasticsearch】elasticsearch教程 es整合springboot教程 kibana安装教程 解决kibana访问404

文章目录linux安装esspringboot-data整合es linux安装es windows启动可能会遇到的报错, 基本和linux是差不多的 可以参考解决方法 官网下载es 。本文以es 7.6 举例 , (es7.15会有api的弃用调整 ,7.15之前的其它7.x版本应该差距较小,但是es大版本之间的差距还是比较大 需要注意api的使用变更) 下载地址 :https://www.elastic.co/products/elasticsearch ,找到历史版本进行下载, 这种网站都时不时

孟秋与你的博客 2676

用FSL的eddy_topup pipeline完整处理DTI数据:从原理到实战,搞定涡流和磁化率畸变

本文详细介绍了如何使用FSL的eddy_topup pipeline完整处理DTI数据,解决涡流和磁化率畸变问题。从原理到实战,涵盖了数据格式转换、脑提取、b0图像处理等关键步骤,并提供了acqparams.txt配置和eddy命令的详细解析,帮助研究人员高效完成DTI数据校正。

weixin_29235525的博客 301

Springboot 整合 Skywalking 和 ElasticSearch

微服务系统中使用 Skywalking 实现链路追踪,并使用 ElasticSearch,Logstash,Kibana 记录产生的日志。

reverb_的博客 1437

Polymarket链上预测市场自动化交易代理开发实战指南

自动化交易代理是量化交易的核心工具,它通过预设的算法规则,自动执行市场分析、决策与下单操作,旨在提升交易效率与纪律性。其技术原理通常涉及实时数据获取、策略引擎计算、交易执行与风险管理等模块的协同工作。在区块链与DeFi领域,这类代理的价值尤为凸显,能够高效处理链上合约交互,捕捉去中心化市场的套利机会。具体到应用场景,链上预测市场如Polymarket,为自动化策略提供了丰富的博弈标的。本文以Polymarket交易代理项目为例,深入剖析其基于Node.js与ethers.js的技术栈实现,详解从环境配置、策

weixin_42533910的博客 591

高通SA8295P音频接口深度解析:全面掌握SA8295P的LS-I2S、PCM/TDM与高性能音频处理技术设计

SA8295P提供丰富的音频接口选项,包括LS-I2S、PCM/TDM和HS-I2S接口,具备灵活的配置选项,适合各种高保真音频和高速数据传输应用。结合LS-I2S和PCM/TDM接口:在复杂的音频编解码器设计中,可结合使用LS-I2S和PCM/TDM接口,以处理和传输不同的音频数据流。使用HS-I2S接口:在软件定义无线电(SDR)系统中,高速I2S接口可处理高速数据流,如无线电信号的解码和处理。LS-I2S(低速I2S)接口是SA8295P的一部分,提供了丰富的音频数据传输选项。

weixin_43199439的博客 1424

ElasticSearch 7.14.0(适合小白的万字笔记!持续更新)

这篇文章是个人在es学习过程中从0-1记录的,非常适合于刚入门的小伙伴,文章涵盖了es和kibana的安装、es基本概念、基础操作、整合SpringBoot、集群等。记录之初是为了加深学习印象。文中包含个人理解如有错误欢迎指出~待补充。。

qq_48079544的博客 1543

广义正态分布优化算法(GNDO)详解:从理论到实践

广义正态分布优化算法(GNDO)是一种基于正态分布理论的新型元启发式优化算法。该算法通过局部开发和全局探索两种策略平衡搜索过程:局部开发利用广义平均位置和标准差进行精细搜索,而全局探索通过随机个体信息共享扩大搜索范围。GNDO具有参数少、结构简单、收敛速度快等优点,在光伏模型参数提取等工程优化问题中表现优异。算法将种群位置更新与正态分布参数调整相联系,通过自适应机制平衡探索与开发,数学分析表明其具有全局收敛性。相比传统优化算法,GNDO在探索能力和开发能力上均有优势,是高维复杂优化问题的有效解决方案。

qq_42212808的博客 151

elasticsearch入门

这篇教程主要是对在入门的elasticsearch的一个记录。 ES 集群安装 安装环境 基于 Dokcer ,单机安装 Docker 版集群。使用版本如下: Elasticsearch 5.3.2 Kibana 5.3.2 JDK 8 整个安装步骤分成三部分: 安装 ES 集群实例 elasticsearch001 安装 ES 集...

weixin_33725126的博客 125

infercnv的实操

摘要: 博主在infercnv分析中遇到执行困难,外包服务不可靠(未按要求使用HMM方法)。通过优化策略(逐样本处理、精简细胞至1000个、固定随机种子)解决了运行问题,但HMM功能仍无法实现。最终参考Cell期刊标准设置阈值完成分析,后续将继续更新进展。该案例凸显了生物信息分析中自主优化的重要性。(150字)

xiaoyusang的博客 315

2026.2.3:OpenClaw国内安装教程,国内网络使用,服务器部署,对接飞书

本文介绍了如何创建飞书应用并接入OpenClaw机器人的完整流程。主要内容包括:1)在飞书开放平台创建企业自建应用,添加机器人能力并开通相关权限;2)在Windows11系统上安装OpenClaw,完成配置文件的修改(需将bind改为"lan");3)配置MiniMax国内接口地址,重启gateway服务。整个过程涵盖了应用创建、权限设置、软件安装、服务配置等关键步骤,为开发者提供了详细的飞书机器人接入指南。

拥抱具身智能,昇腾Ascend C 4019

ElasticSearch 快速上手攻略(零基础落地版)

掌握基础概念:索引、文档、映射、分词、倒排索引原理熟练使用 Kibana 完成 CRUD、条件检索、高亮、排序分页安装 IK 分词器,掌握中文检索配置整合 SpringBoot 实现代码级检索、新增、修改学习聚合查询、批量操作、分页优化、集群基础配置(注:部分内容可能由 AI 生成)

2301_78638502的博客 236

【硬件的单元测试 UT 3】PCIe 3.0及信号完整性测试方法

PCIe标准自从推出以来,1代和2代标准已经在PC和Server上逐渐普及,用于满足高速显卡、高速存储设备对于高速数据传输的要求。出于支持更高总线数据吞吐率的目的,PCI-SIG组织在2010年制定了PCIe 3.0,即PCIe 3代的规范,数据速率达到8Gbps。

qq_43416206的博客 1432

【Elastic-1】ELK基本概念、环境搭建、快速开始文档

TODO 快速开始文档 SpringBoot整合ELK(Logstash收集日志、应用主动向ES写入) ELK接入Kafka 基本概念 ElasticSearch 什么是ElasticSearch? 首推官网的解释: https://www.elastic.co/guide/en/elasticsearch/reference/7.11/elasticsearch-intro.html...

耶low的博客 406

8、 使用TPM密钥:从理论到实践的全面指南

本文全面介绍了如何使用TPM(可信平台模块)进行密钥管理,涵盖密钥的创建、存储、加载、迁移以及特殊密钥类型的使用。通过详细的操作步骤和代码示例,帮助读者掌握TPM密钥管理技术,确保系统的安全性和可靠性。

weixin_36212459的博客 250

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

长路的Java后端技术博客汇总文档

本博客由长路倾力打造,涵盖Java基础、算法、分布式微服务、数据库、框架等核心技术内容。从初学者到进阶开发者,提供全方位学习资源,助力技术提升与职业发展。

每个人都是独一无二的,把握好自己的节奏,跟着自己的心走。 1681

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

基于YOLOv8/v10/v11/v12/26的森林野外火灾火焰烟雾检测系统(Spring Boot+Vue+Flask+DeepSeek+千问大模型)完整实现与模型对比分析

基于YOLOv8/v10/v11/v12/26的森林野外火灾火焰烟雾检测系统(Spring Boot+Vue+Flask+DeepSeek+千问大模型)完整实现与模型对比分析

斌擎科技 498

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

springboot整合elasticsearch8

springboot整合elasticsearch8

winsanity的博客 4727

【ElasticSearch8】SpringBoot集成ElasticSearch8.x 基本应用(环境安装和CRUD操作)

最近在研究es的时候发现官方已经在7.15.0放弃对旧版本中的Java REST Client (High Level Rest Client (HLRC))的支持,从而替换为推荐使用的Java API Client 8.x。查看SpringBoot2.6.4的依赖,其中es的版本仅为7.15.2。</</</</因此这里我就按照官方文档使用了推荐的。</</</</鉴于es8.x的资料文档目前并不是很齐全,本文中如有错误,欢迎各位指出。本文将记录一些es8.x api下的简单CRUD操作。

weixin_45131680的博客 3223

SpringBoot集成Elasticsearch8.x(7)|(新版本Java API Client使用完整示例)

在Es7.15版本之后,es官方将它的高级客户端RestHighLevelClient标记为弃用状态。同时推出了全新的java API客户端Elasticsearch Java API Client,该客户端也将在Elasticsearch8.0及以后版本中成为官方推荐使用的客户端。定义一个实体,用于向ES中存储数据@Data@Builder} ## 4. 调用测试实现 > 实现索引的创建以及数据的存储查询示例```c"ES操作" }) @RestController。

Oaklkm的博客 1万+

重学SpringBoot3-整合 Elasticsearch 8.x (一)客户端方式

Spring Boot 3 中推荐使用 Spring Data Elasticsearch 提供的客户端来访问 Elasticsearch,而不再使用低层次的 Transport Client。Elasticsearch 8.x 推出后,官方推荐使用 Java REST Client 和 ElasticsearchClient,Spring Data Elasticsearch 也支持这些新的客户端。在 Spring Boot 3 中集成 Elasticsearch 8.x 可以通过多种方式实现,包括。

CoderJia的学习之路 5477
上一篇: Windows 安装并配置 MySQL 5.7
下一篇: 解决tomcat启动慢的问题
男人不容易
博客等级 码龄13年 14粉丝 10原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

男人不容易

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值