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

2024-03-16 09:52

本文主要是介绍SpringBoot3整合Elasticsearch8.x之全面保姆级教程,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

整合ES

环境准备

  1. 安装配置EShttps://blog.csdn.net/qq_50864152/article/details/136724528
  2. 安装配置Kibanahttps://blog.csdn.net/qq_50864152/article/details/136727707
  3. 新建项目:新建名为webSpringBoot3项目

elasticsearch-java

公共配置

  1. 介绍:一个开源的高扩展的分布式全文检索引擎,可以近乎实时的存储 和检索数据
  2. 依赖:web模块引入elasticsearch-java依赖---但其版本必须与你下载的ES的版本一致
<!-- 若不存在Spring Data ES的某个版本支持你下的ES版本,则使用  -->
<!-- ES 官方提供的在JAVA环境使用的依赖 -->
<dependency><groupId>co.elastic.clients</groupId><artifactId>elasticsearch-java</artifactId><version>8.11.1</version>
</dependency><!-- 和第一个依赖是一起的,为了解决springboot项目的兼容性问题  -->
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId>
</dependency>
  1. 配置:web模块dev目录application-dal添加

使用open+@Value("${elasticsearch.open}")的方式不能放到Nacos配置中心

# elasticsearch配置
elasticsearch:# 自定义属性---设置是否开启ES,false表不开窍ESopen: true# es集群名称,如果下载es设置了集群名称,则使用配置的集群名称clusterName: eshosts: 127.0.0.1:9200# es 请求方式scheme: http# es 连接超时时间connectTimeOut: 1000# es socket 连接超时时间socketTimeOut: 30000# es 请求超时时间connectionRequestTimeOut: 500# es 最大连接数maxConnectNum: 100# es 每个路由的最大连接数maxConnectNumPerRoute: 100
  1. 配置:web模块config包下新建ElasticSearchConfig
package cn.bytewisehub.pai.web.config;import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
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.RestClientBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Slf4j
@Data
@Configuration
@ConfigurationProperties(prefix = "elasticsearch")
public class ElasticSearchConfig {// 是否开启ESprivate Boolean open;// es 集群host ip 地址private String hosts;// es用户名private String userName;// es密码private String password;// es 请求方式private String scheme;// es集群名称private String clusterName;// es 连接超时时间private int connectTimeOut;// es socket 连接超时时间private int socketTimeOut;// es 请求超时时间private int connectionRequestTimeOut;// es 最大连接数private int maxConnectNum;// es 每个路由的最大连接数private int maxConnectNumPerRoute;// es api keyprivate String apiKey;public RestClientBuilder creatBaseConfBuilder(String scheme){// 1. 单节点ES Host获取String host = hosts.split(":")[0];String port = hosts.split(":")[1];// The value of the schemes attribute used by noSafeRestClient() is http// but The value of the schemes attribute used by safeRestClient() is httpsHttpHost httpHost = new HttpHost(host, Integer.parseInt(port),scheme);// 2. 创建构建器对象//RestClientBuilder: ES客户端库的构建器接口,用于构建RestClient实例;允许你配置与Elasticsearch集群的连接,设置请求超时,设置身份验证,配置代理等RestClientBuilder builder = RestClient.builder(httpHost);// 连接延时配置builder.setRequestConfigCallback(requestConfigBuilder -> {requestConfigBuilder.setConnectTimeout(connectTimeOut);requestConfigBuilder.setSocketTimeout(socketTimeOut);requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeOut);return requestConfigBuilder;});// 3. HttpClient 连接数配置builder.setHttpClientConfigCallback(httpClientBuilder -> {httpClientBuilder.setMaxConnTotal(maxConnectNum);httpClientBuilder.setMaxConnPerRoute(maxConnectNumPerRoute);return httpClientBuilder;});return builder;}
}
  1. 测试:web模块test目录下新建ElasticSearchTest
@Slf4j
@SpringBootTest
public class ElasticSearchTest {@Value("${elasticsearch.open}")// 是否开启ES,默认开启String open = "true";
}

直接连接ES

  1. 设置:ES Elasticsearch.ymlxpack.security.enabled属性设置为false

xpack.security.enabled
● 默认true:必须使用账号连接ES
● 若为false:必须使用http://localhost:9200/访问ES服务+启动Kibana服务会失败+不需要使用账号连接,但必须使用HTTP连接

  1. 添加:ElasticSearchConfig类添加下列方法
/**
* @function: 创建使用http连接来直接连接ES服务器的客户端
* 如果@Bean没有指定bean的名称,那么这个bean的名称就是方法名
*/
@Bean(name = "directConnectionESClient")
public ElasticsearchClient directConnectionESClient(){RestClientBuilder builder = creatBaseConfBuilder((scheme == "http")?"http":"http");//Create the transport with a Jackson mapperElasticsearchTransport transport = new RestClientTransport(builder.build(), new JacksonJsonpMapper());//And create the API clientElasticsearchClient esClient = new ElasticsearchClient(transport);return esClient;
};
  1. 添加:ElasticSearchTest类中添加下列代码---索引名必须小写
  2. 运行:设置跳过测试--->手动运行/不跳过--->直接install,但不运行测试
@Resource(name = "directConnectionESClient")
ElasticsearchClient directConnectionESClient;@Test
public void directConnectionTest() throws IOException {if (open.equals("true")) {//创建索引CreateIndexResponse response = directConnectionESClient.indices().create(c -> c.index("direct_connection_index"));log.info(response.toString());
}
else{log.info("es is closed");
}
}

账号密码连接ES

  1. 设置:ES Elasticsearch.ymlxpack.security.enabled属性使用默认值+ xpack.security.http.ssl.enabled设置为false

注意:若xpack.security.enabled属性为false,则xpack.security.http.ssl.enabled属性不生效,即相当于设置为false;所有以xpack开头的属性都不会生效

ES Elasticsearch.ymlxpack.security.http.ssl.enabled
● 默认true:必须使用https://localhost:9200/访问ES服务+启动Kibana服务会成功+需要使用账号连接+必须使用HTTPS连接
● 若为false:必须使用http://localhost:9200/访问ES服务+启动Kibana服务会失败+需要使用账号连接,但必须使用HTTP连接

  1. 配置:dev目录application-dal中添加下列配置
# elasticsearch配置
elasticsearch:userName:  #自己的账号名password:  #自己的密码
  1. 添加:ElasticSearchTest类中添加下列代码---索引名必须小写+不能有空格
  2. 运行:设置跳过测试--->手动运行/不跳过--->直接install,但不运行测试
@Resource(name = "accountConnectionESClient")
ElasticsearchClient accountConnectionESClient;@Test
public void accountConnectionTest() throws IOException {if (open.equals("true")) {//创建索引CreateIndexResponse response = accountConnectionESClient.indices().create(c -> c.index("account_connection_index"));log.info(response.toString());
}
else{log.info("es is closed");
}
}

证书账号连接ES

  1. 设置:ES Elasticsearch.ymlxpack.security.enabledxpack.security.http.ssl.enabled配置项使用默认值

设置为true后,ES就走https,若schemehttp,则报Unrecognized SSL message错误

  1. 配置:将dev目录application-dalelasticsearch.scheme配置项改成https
  2. 证书添加:终端输入keytool -importcert -alias es_https_ca -keystore "D:\computelTool\Java\JDK\JDK21\lib\security\cacerts" -file "D:\computelTool\database\elasticsearch8111\config\certs\http_ca.crt"

keytool -delete -alias es_https_ca -keystore "D:\computelTool\Java\JDK\JDK21\lib\security\cacerts" ---与上面的命令相反

  1. 拷贝:将ESconfig目录下certs目录下的http_ca.crt文件拷贝到web模块resource目录
  2. 添加:ElasticSearchConfig类添加下列方法
/**
* @function: 创建用于安全连接(证书 + 账号)ES服务器的客户端
* 如果@Bean没有指定bean的名称,那么这个bean的名称就是方法名
*/
@Bean(name = "accountAndCertificateConnectionESClient")
public ElasticsearchClient accountAndCertificateConnectionESClient() {RestClientBuilder builder = creatBaseConfBuilder( (scheme == "https")?"https":"https");// 1.账号密码的配置//CredentialsProvider: 用于提供 HTTP 身份验证凭据的接口; 允许你配置用户名和密码,以便在与服务器建立连接时进行身份验证CredentialsProvider credentialsProvider = new BasicCredentialsProvider();credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));// 2.设置自签证书,并且还包含了账号密码builder.setHttpClientConfigCallback(httpAsyncClientBuilder -> httpAsyncClientBuilder.setSSLContext(buildSSLContext()).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setDefaultCredentialsProvider(credentialsProvider));RestClientTransport transport = new RestClientTransport(builder.build(), new JacksonJsonpMapper());//And create the API clientElasticsearchClient esClient = new ElasticsearchClient(transport);return esClient;
}private static SSLContext buildSSLContext() {// 读取http_ca.crt证书ClassPathResource resource = new ClassPathResource("http_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, "liuxiansheng".toCharArray());trustStore.setCertificateEntry("ca", trustedCa);SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null);sslContext = sslContextBuilder.build();} catch (CertificateException | IOException | KeyStoreException | NoSuchAlgorithmException |KeyManagementException e) {log.error("ES连接认证失败", e);}return sslContext;
}
  1. 测试:ElasticSearchTest类添加
@Resource(name = "accountAndCertificateConnectionESClient")
ElasticsearchClient accountAndCertificateConnectionESClient;@Test
public void  accountAndCertificateConnectionTest() throws IOException {if (open.equals("true")) {//创建索引CreateIndexResponse response =  accountAndCertificateConnectionESClient.indices().create(c -> c.index("account_and_certificate_connection_index"));log.info(response.toString());System.out.println(response.toString());
}
else{log.info("es is closed");
}
}

Spring Data ES

公共配置

  1. 依赖:web模块引入该依赖---但其版本必须与你下载的ES的版本一致

版本:点击https://spring.io/projects/spring-data-elasticsearch#learn,点击GA版本的Reference Doc,点击version查看Spring Data ESES版本的支持关系

参考:https://www.yuque.com/itwanger/vn4p17/wslq2t/https://blog.csdn.net/qq_40885085/article/details/105023026

<!-- 若存在Spring Data ES的某个版本支持你下的ES版本,则使用  -->
<!-- Spring官方在ES官方提供的JAVA环境使用的依赖的基础上做了封装 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency><!-- ESTestEntity用到 -->
<dependency><groupId>jakarta.servlet</groupId><artifactId>jakarta.servlet-api</artifactId><version>6.0.0</version><scope>provided</scope>
</dependency><!-- ESTestEntity用到 -->
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><scope>provided</scope><!--provided:指定该依赖项在编译时是必需的,才会生效, 但在运行时不需要,也不会生效--><!--这样 Lombok 会在编译期静悄悄地将带 Lombok 注解的源码文件正确编译为完整的 class 文件 -->
</dependency>
  1. 新建:web模块TestEntity目录新建ESTestEntity
@Data
@EqualsAndHashCode(callSuper = false)
@Document(indexName = "test")
public class ESTestEntity implements Serializable {private static final long serialVersionUID = 1L;@Idprivate Long id;@Field(type = FieldType.Text, analyzer = "ik_max_word")private String content;private String title;private String excerpt;
}
  1. 新建:web模块TestRepository包下新建ESTestRepository 接口
import cn.bytewisehub.pai.web.TestEntity.ESTestEntity;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;public interface ESTestRepository extends ElasticsearchRepository<ESTestEntity, Long> {
}

直接连接ES

  1. 配置:ES Elasticsearch.ymlxpack.security.enabled属性设置为false

xpack.security.enabled
● 默认true:必须使用账号连接ES
● 若为false:必须使用http://localhost:9200/访问ES服务+启动Kibana服务会失败+不需要使用账号连接,但必须使用HTTP连接

  1. 配置:web模块dev目录application-dal添加
spring:elasticsearch:uris:- http://127.0.0.1:9200
  1. 新建:web模块test目录新建ElasticsearchTemplateTest
import cn.bytewisehub.pai.web.TestEntity.ESTestEntity;
import cn.bytewisehub.pai.web.TestRepository.ESTestRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;@SpringBootTest
public class ElasticsearchTemplateTest {@AutowiredESTestRepository esTestRepository;@AutowiredElasticsearchTemplate elasticsearchTemplate;@Testvoid save() {ESTestEntity esTestEntity = new ESTestEntity();esTestEntity.setId(1L);esTestEntity.setContent("不安全连接");esTestEntity.setTitle("world");esTestEntity.setExcerpt("test");System.out.println(elasticsearchTemplate.save(esTestEntity));}@Testvoid insert() {ESTestEntity esTestEntity = new ESTestEntity();esTestEntity.setId(2L);esTestEntity.setContent("不安全连接");esTestEntity.setTitle("world");esTestEntity.setExcerpt("test");System.out.println(esTestRepository.save(esTestEntity));}
}
  1. 访问:点击http://localhost:9200/test/_search ---查询索引库test
    请添加图片描述

HTTP连接ES

  1. 配置:ES Elasticsearch.ymlxpack.security.enabled属性使用默认值+ xpack.security.http.ssl.enabled设置为false

ES Elasticsearch.ymlxpack.security.http.ssl.enabled
● 默认true:必须使用https://localhost:9200/访问ES服务+启动Kibana服务会成功+需要使用账号连接+必须使用HTTPS连接
● 若为false:必须使用http://localhost:9200/访问ES服务+启动Kibana服务会失败+需要使用账号连接,但必须使用HTTP连接

  1. 配置:web模块dev目录application-dal添加
spring:elasticsearch:uris:- http://127.0.0.1:9200username:  # 账号用户名password:  #账号密码
  1. 修改:web模块test目录下ElasticsearchTemplateTest修改成这样,其他参见直接连接
import cn.bytewisehub.pai.web.TestEntity.ESTestEntity;
import cn.bytewisehub.pai.web.TestRepository.ESTestRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;@SpringBootTest
public class ElasticsearchTemplateTest {@AutowiredESTestRepository esTestRepository;@AutowiredElasticsearchTemplate elasticsearchTemplate;@Testvoid save() {ESTestEntity esTestEntity = new ESTestEntity();esTestEntity.setId(1L);esTestEntity.setContent("不安全连接");esTestEntity.setTitle("world");esTestEntity.setExcerpt("test");System.out.println(elasticsearchTemplate.save(esTestEntity));}@Testvoid insert() {ESTestEntity esTestEntity = new ESTestEntity();esTestEntity.setId(2L);esTestEntity.setContent("不安全连接");esTestEntity.setTitle("world");esTestEntity.setExcerpt("test");System.out.println(esTestRepository.save(esTestEntity));}
}
  1. 访问:点击http://localhost:9200/test/_search ---查询索引库test

HTTPS连接ES

  1. 配置:ES Elasticsearch.ymlxpack.security.enabledxpack.security.http.ssl.enabled属性使用默认值
  2. 配置:web模块dev目录application-dal添加
spring:elasticsearch:uris:- https://127.0.0.1:9200username:  # 账号用户名password:  #账号密码
  1. 修改:web模块test目录下ElasticsearchTemplateTest修改成这样,其他参见直接连接
import cn.bytewisehub.pai.web.TestEntity.ESTestEntity;
import cn.bytewisehub.pai.web.TestRepository.ESTestRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;@SpringBootTest
public class ElasticsearchTemplateTest {@AutowiredESTestRepository esTestRepository;@AutowiredElasticsearchTemplate elasticsearchTemplate;@Testvoid save() {ESTestEntity esTestEntity = new ESTestEntity();esTestEntity.setId(1L);esTestEntity.setContent("不安全连接");esTestEntity.setTitle("world");esTestEntity.setExcerpt("test");System.out.println(elasticsearchTemplate.save(esTestEntity));}@Testvoid insert() {ESTestEntity esTestEntity = new ESTestEntity();esTestEntity.setId(2L);esTestEntity.setContent("不安全连接");esTestEntity.setTitle("world");esTestEntity.setExcerpt("test");System.out.println(esTestRepository.save(esTestEntity));}
}
  1. 访问:点击http://localhost:9200/test/_search ---查询索引库test

这篇关于SpringBoot3整合Elasticsearch8.x之全面保姆级教程的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/815095

相关文章

使用Docker构建Python Flask程序的详细教程

《使用Docker构建PythonFlask程序的详细教程》在当今的软件开发领域,容器化技术正变得越来越流行,而Docker无疑是其中的佼佼者,本文我们就来聊聊如何使用Docker构建一个简单的Py... 目录引言一、准备工作二、创建 Flask 应用程序三、创建 dockerfile四、构建 Docker

Java操作Word文档的全面指南

《Java操作Word文档的全面指南》在Java开发中,操作Word文档是常见的业务需求,广泛应用于合同生成、报表输出、通知发布、法律文书生成、病历模板填写等场景,本文将全面介绍Java操作Word文... 目录简介段落页头与页脚页码表格图片批注文本框目录图表简介Word编程最重要的类是org.apach

SpringBoot整合liteflow的详细过程

《SpringBoot整合liteflow的详细过程》:本文主要介绍SpringBoot整合liteflow的详细过程,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋...  liteflow 是什么? 能做什么?总之一句话:能帮你规范写代码逻辑 ,编排并解耦业务逻辑,代码

Linux中SSH服务配置的全面指南

《Linux中SSH服务配置的全面指南》作为网络安全工程师,SSH(SecureShell)服务的安全配置是我们日常工作中不可忽视的重要环节,本文将从基础配置到高级安全加固,全面解析SSH服务的各项参... 目录概述基础配置详解端口与监听设置主机密钥配置认证机制强化禁用密码认证禁止root直接登录实现双因素

全面解析MySQL索引长度限制问题与解决方案

《全面解析MySQL索引长度限制问题与解决方案》MySQL对索引长度设限是为了保持高效的数据检索性能,这个限制不是MySQL的缺陷,而是数据库设计中的权衡结果,下面我们就来看看如何解决这一问题吧... 目录引言:为什么会有索引键长度问题?一、问题根源深度解析mysql索引长度限制原理实际场景示例二、五大解决

springboot整合TDengine全过程

《springboot整合TDengine全过程》:本文主要介绍springboot整合TDengine全过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录环境准备JDBC-JNI方式准备依赖实体类Mapper配置类测试类RESTful方式实体类配置类测试类总结

MySQL追踪数据库表更新操作来源的全面指南

《MySQL追踪数据库表更新操作来源的全面指南》本文将以一个具体问题为例,如何监测哪个IP来源对数据库表statistics_test进行了UPDATE操作,文内探讨了多种方法,并提供了详细的代码... 目录引言1. 为什么需要监控数据库更新操作2. 方法1:启用数据库审计日志(1)mysql/mariad

深度解析Spring AOP @Aspect 原理、实战与最佳实践教程

《深度解析SpringAOP@Aspect原理、实战与最佳实践教程》文章系统讲解了SpringAOP核心概念、实现方式及原理,涵盖横切关注点分离、代理机制(JDK/CGLIB)、切入点类型、性能... 目录1. @ASPect 核心概念1.1 AOP 编程范式1.2 @Aspect 关键特性2. 完整代码实

Java Web实现类似Excel表格锁定功能实战教程

《JavaWeb实现类似Excel表格锁定功能实战教程》本文将详细介绍通过创建特定div元素并利用CSS布局和JavaScript事件监听来实现类似Excel的锁定行和列效果的方法,感兴趣的朋友跟随... 目录1. 模拟Excel表格锁定功能2. 创建3个div元素实现表格锁定2.1 div元素布局设计2.

SpringBoot连接Redis集群教程

《SpringBoot连接Redis集群教程》:本文主要介绍SpringBoot连接Redis集群教程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1. 依赖2. 修改配置文件3. 创建RedisClusterConfig4. 测试总结1. 依赖 <de