Spring Boot 集成 Elasticsearch 全攻略
nanshan 2025-07-03 18:19 12 浏览 0 评论
在当今大数据和高并发的时代背景下,高效的数据检索和分析成为众多应用系统的核心需求。Elasticsearch(简称 ES)作为一款开源的分布式搜索引擎,以其强大的全文检索、实时分析和水平扩展能力,受到了开发者们的广泛青睐。而 Spring Boot 凭借其快速构建、自动配置的特性,极大地简化了 Java 应用的开发过程。将 Spring Boot 与 Elasticsearch 集成,能够充分发挥两者的优势,为应用系统提供高效、灵活的数据检索解决方案。接下来,我们就详细介绍如何在 Spring Boot 项目中集成 Elasticsearch。
一、环境准备
在开始集成之前,确保你已经安装好了以下环境:
- JDK:推荐使用 JDK 8 及以上版本。
- Elasticsearch:下载并安装合适版本的 Elasticsearch,安装完成后启动 ES 服务。可以通过访问http://localhost:9200/,若能看到 ES 的欢迎信息,说明 ES 服务正常运行。
- Spring Boot 项目:可以通过 Spring Initializr(https://start.spring.io/)创建一个基础的 Spring Boot 项目,在创建时勾选Spring Data Elasticsearch依赖,方便后续集成。
二、添加依赖
如果在创建 Spring Boot 项目时没有勾选Spring Data Elasticsearch依赖,也可以在项目的pom.xml文件中手动添加:
<dependencies> <!-- Spring Data Elasticsearch 依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> <!-- Spring Boot 测试依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> |
添加完依赖后,Maven 会自动下载相关的 jar 包。
三、配置 Elasticsearch 连接
在application.properties或application.yml文件中配置 Elasticsearch 的连接信息。以application.yml为例:
spring: data: elasticsearch: cluster-name: elasticsearch # ES集群名称,默认为elasticsearch cluster-nodes: localhost:9300 # ES节点地址,9300为传输端口,若使用默认配置可不修改 # 或者使用以下配置方式,适用于REST API连接 # uri: http://localhost:9200 |
如果使用的是 Elasticsearch 的 REST API 进行交互,也可以使用uri配置项,直接指定 ES 的 HTTP 访问地址。
四、创建实体类
创建一个 Java 实体类,用于映射 Elasticsearch 中的文档。假设我们有一个简单的博客文章实体类Blog:
import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; @Document(indexName = "blog", type = "_doc", shards = 1, replicas = 0) public class Blog { @Id private String id; @Field(type = FieldType.Text) private String title; @Field(type = FieldType.Text) private String content; // 省略getter和setter方法 } |
在上述代码中:
- @Document注解用于定义该实体类对应的 Elasticsearch 索引名称、文档类型、分片数和副本数。
- @Id注解标识该字段为文档的唯一标识。
- @Field注解用于指定字段的类型等属性,这里将title和content字段定义为Text类型,适合进行全文检索。
五、创建 Repository 接口
创建一个继承自ElasticsearchRepository的接口,用于对 Elasticsearch 进行数据操作:
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import java.util.List; public interface BlogRepository extends ElasticsearchRepository<Blog, String> { List<Blog> findByTitleContaining(String keyword); } |
在这个接口中,我们定义了一个自定义方法findByTitleContaining,它会根据方法名的约定,自动生成查询语句,用于查找标题中包含指定关键字的博客文章。同时,ElasticsearchRepository已经提供了许多常用的 CRUD 操作方法,如save、findById、delete等,可以直接使用。
六、编写业务逻辑和测试代码
在服务类中注入BlogRepository,并编写业务逻辑方法。例如,创建一个BlogService类:
import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class BlogService { private final BlogRepository blogRepository; public BlogService(BlogRepository blogRepository) { this.blogRepository = blogRepository; } public Blog saveBlog(Blog blog) { return blogRepository.save(blog); } public Optional<Blog> findBlogById(String id) { return blogRepository.findById(id); } public List<Blog> searchBlogs(String keyword) { return blogRepository.findByTitleContaining(keyword); } public void deleteBlogById(String id) { blogRepository.deleteById(id); } } |
接下来,可以编写测试代码对集成功能进行验证。在src/test/java目录下的测试类中编写如下测试方法:
import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; @SpringBootTest public class BlogServiceTest { @Autowired private BlogService blogService; @Test public void testSaveAndFindBlog() { Blog blog = new Blog(); blog.setTitle("Spring Boot集成ES测试文章"); blog.setContent("这是一篇用于测试的文章内容"); Blog savedBlog = blogService.saveBlog(blog); assertNotNull(savedBlog.getId()); Optional<Blog> retrievedBlog = blogService.findBlogById(savedBlog.getId()); assertTrue(retrievedBlog.isPresent()); assertEquals("Spring Boot集成ES测试文章", retrievedBlog.get().getTitle()); } @Test public void testSearchBlogs() { Blog blog1 = new Blog(); blog1.setTitle("Spring Boot入门教程"); blog1.setContent("详细介绍Spring Boot入门知识"); blogService.saveBlog(blog1); Blog blog2 = new Blog(); blog2.setTitle("Elasticsearch实战"); blog2.setContent("分享Elasticsearch的实战经验"); blogService.saveBlog(blog2); List<Blog> searchResults = blogService.searchBlogs("Spring Boot"); assertEquals(1, searchResults.size()); assertEquals("Spring Boot入门教程", searchResults.get(0).getTitle()); } } |
运行这些测试方法,如果都能顺利通过,说明 Spring Boot 与 Elasticsearch 的集成基本成功。
七、高级配置与优化
1. 自定义 ElasticsearchTemplate
除了使用ElasticsearchRepository,还可以通过ElasticsearchTemplate进行更灵活的操作。在配置类中注入ElasticsearchTemplate:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories; @Configuration @EnableElasticsearchRepositories(basePackages = "com.example.demo.repository") public class ElasticsearchConfig { @Bean public ElasticsearchTemplate elasticsearchTemplate() { return new ElasticsearchTemplate(elasticsearchClient()); } // 省略elasticsearchClient方法的定义,根据实际连接方式编写 } |
然后在业务类中注入ElasticsearchTemplate,就可以使用它执行复杂的查询、聚合等操作。
2. 性能优化
- 索引设置优化:合理设置索引的分片数和副本数,根据数据量和查询负载进行调整。一般来说,分片数在创建索引后不能轻易修改,而副本数可以动态调整。
- 批量操作:对于大量数据的插入或更新,可以使用ElasticsearchRepository的批量操作方法,或者通过ElasticsearchTemplate执行批量请求,减少与 ES 的交互次数,提高性能。
- 缓存策略:对于一些不经常变化的数据,可以在应用层添加缓存,减少对 Elasticsearch 的查询压力。
八、常见问题与解决
1. 连接超时问题
如果出现连接 Elasticsearch 超时的情况,可能是 ES 服务未正常启动,或者网络配置有误。检查 ES 服务状态,确保cluster-nodes或uri配置的地址和端口正确。如果 ES 设置了安全认证,还需要在连接配置中添加用户名和密码。
2. 映射冲突问题
当实体类的字段类型与 Elasticsearch 索引的映射不匹配时,会出现映射冲突。可以通过手动创建索引并定义映射,或者使用ElasticsearchTemplate的putMapping方法动态更新映射。
3. 依赖版本兼容问题
Spring Data Elasticsearch 与 Elasticsearch 的版本需要保持兼容,否则可能会出现各种异常。在选择依赖版本时,参考官方文档的版本兼容性说明。
通过以上步骤,我们完成了 Spring Boot 与 Elasticsearch 的集成,并实现了基本的数据操作和查询功能。在实际项目中,可以根据具体需求进一步扩展和优化,利用 Elasticsearch 强大的搜索和分析能力,为应用系统提供更高效的数据服务。
以上就是 Spring Boot 集成 ES 的完整流程与要点。若你在实践中遇到特定问题,或想了解某部分的拓展内容,欢迎随时和我说。
相关推荐
- 三种自建KMS激活系统自动激活windows方法
-
第一种:在windows服务器上搭建主要针对vol版本(win7、win10、win20xx、win2012等等)平台:我自己搭建的windows虚拟机,windows2016的操作系统软件:...
- 重装系统被收98元?避开Windows付费陷阱的实用指南
-
重装系统被收98元?避开Windows付费陷阱的实用指南有网友反映,在重装Windows系统后,屏幕突然弹出“激活系统需支付98元服务费”的提示,疑惑自己是不是遭遇了付费陷阱。事实上,微软官方的Wi...
- Windows Server2012远程桌面服务配置和授权激活
-
安装:注意:安装完毕之后需手动重启一下计算机配置终端服务管理工具---远程桌面服务---RD授权诊断程序,查看当前服务器有没有授权授权:运行—>gpedit.msc->计算机配置---管理...
- 新书速览|Windows Server 2022 系统与网站配置实战
-
讲述桌面体验、ServerCore/NanoServer,容器与云系统的配置1本书内容《WindowsServer2022系统与网站配置实战》秉持作者一贯理论兼具实践的写作风格,以新版的Wi...
- Windows激活全攻略:KMS神钥与专业工具的完美结合!
-
对于许多Windows用户来说,系统的激活是一个必经的过程。虽然Windows操作系统在未经激活的状态下也可以使用一段时间,但长期来看,未激活的系统会限制某些功能并频繁提示用户激活。以下是两种流行的激...
- 微软Win9全新激活技术曝光(微软系统激活有什么用)
-
2014-07-0905:46:00作者:徐日俄罗斯Wzor日前披露了更多关于Windows9的最新消息,据悉,Windows9将会在今年秋季亮相,其宣传口号是“想要开始按钮和开始菜单?如你所...
- 快速激活Windows 10/11:CMD命令详细教程
-
#记录我的2024#激活Windows操作系统是确保系统功能和安全更新正常运行的重要步骤。本文将为您分享如何使用命令提示符(CMD)在Windows10和Windows11上进行激活的详细步骤。...
- Wndows 2019 RDS应用发布部署(rds的安装和应用程序的发布)
-
安装前的准备1、需要提供服务器作为应用中心,应用中心的推荐配置如下表所示。规格建议1-10人11-20人21-50人51-100人100+人CPU4核8核16核内存8GB16GB32GB64GB系统盘...
- 解决 Windows 系统激活难题(如何解决windows激活问题)
-
今天,一位朋友给我说,他手头有三台电脑,均同时弹出系统未激活的提示。他对此毫无头绪,便急忙将电脑上出现的激活提示信息一股脑发给了我。我看到其中一台显示的是“Windows10企业版LTSC尚...
- 自建KMS激活服务器(自建kms激活服务器的风险)
-
自建KMS激活服务器Win10和office安装后,都需要激活才可以使用,一般可以输入购买的MAK激活码进行在线激活,也可以通过KMS激活,网上也有很多激活工具,但这些工具一般都含有病毒或木马程序,容...
- 30秒免费激活windows和office亲测有效!
-
“第三方工具有病毒?”“KMS服务器激活总失效?”今天给大家分享一个开源激活工具——MicrosoftActivationScripts(MAS),无需密钥、不装软件,30秒永久激活Window...
- 「操作系统」Windows 10 LTSC 2019 企业版C大集成更新版
-
Windows10LTSC企业版CHIANNET集成更新优化整合多镜像版,CHIANNET,是USBOS超级PE维护盘工具箱作者,长久以来一直默默的更新着,USBOSPE软件,电脑城装机及...
- 一文看懂Windows激活:自查方法+授权类型科普(Win7/Win10通用)
-
一、如何判断Windows是否永久激活?无论是Win7还是Win10,均可通过以下方法快速验证:命令提示符法(通用):按下Win+R,输入slmgr.vbs/xpr并按回车键运行即可查看是否...
- 部分Windows Server 2019/2022用户反馈无法运行微软Teams应用
-
IT之家7月2日消息,科技媒体borncity今天(7月2日)发布博文,报道称在多个WindowsServer版本上,MicrosoftTeams应用近期出现了运行故障。用...
- 这种Windows激活方式已有20年...(windows现在激活)
-
2006年微软正式发布WindowsVista,随之而来引入了一项新的激活机制「OEM激活」,这项机制在Vista和Win7上最为流行。其实WindowsServer自2008开始至2025版本一...
你 发表评论:
欢迎- 一周热门
-
-
UOS服务器操作系统防火墙设置(uos20关闭防火墙)
-
极空间如何无损移机,新Z4 Pro又有哪些升级?极空间Z4 Pro深度体验
-
手机如何设置与显示准确时间的详细指南
-
NAS:DS video/DS file/DS photo等群晖移动端APP远程访问的教程
-
如何在安装前及安装后修改黑群晖的Mac地址和Sn系列号
-
如何修复用户配置文件服务在 WINDOWS 上登录失败的问题
-
一加手机与电脑互传文件的便捷方法FileDash
-
日本海上自卫队的军衔制度(日本海上自卫队的军衔制度是什么)
-
10个免费文件中转服务站,分享文件简单方便,你知道几个?
-
爱折腾的特斯拉车主必看!手把手教你TESLAMATE的备份和恢复
-
- 最近发表
-
- 三种自建KMS激活系统自动激活windows方法
- 重装系统被收98元?避开Windows付费陷阱的实用指南
- Windows Server2012远程桌面服务配置和授权激活
- 新书速览|Windows Server 2022 系统与网站配置实战
- Windows激活全攻略:KMS神钥与专业工具的完美结合!
- 微软Win9全新激活技术曝光(微软系统激活有什么用)
- 快速激活Windows 10/11:CMD命令详细教程
- Wndows 2019 RDS应用发布部署(rds的安装和应用程序的发布)
- 解决 Windows 系统激活难题(如何解决windows激活问题)
- 自建KMS激活服务器(自建kms激活服务器的风险)
- 标签列表
-
- linux 查询端口号 (58)
- docker映射容器目录到宿主机 (66)
- 杀端口 (60)
- yum更换阿里源 (62)
- internet explorer 增强的安全配置已启用 (65)
- linux自动挂载 (56)
- 禁用selinux (55)
- sysv-rc-conf (69)
- ubuntu防火墙状态查看 (64)
- windows server 2022激活密钥 (56)
- 无法与服务器建立安全连接是什么意思 (74)
- 443/80端口被占用怎么解决 (56)
- ping无法访问目标主机怎么解决 (58)
- fdatasync (59)
- 405 not allowed (56)
- 免备案虚拟主机zxhost (55)
- linux根据pid查看进程 (60)
- dhcp工具 (62)
- mysql 1045 (57)
- 宝塔远程工具 (56)
- ssh服务器拒绝了密码 请再试一次 (56)
- ubuntu卸载docker (56)
- linux查看nginx状态 (63)
- tomcat 乱码 (76)
- 2008r2激活序列号 (65)