问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

Spring Boot 2.x集成Elasticsearch教程:Spring Data方式

创作时间:
2025-01-22 01:52:25
作者:
@小白创作中心

Spring Boot 2.x集成Elasticsearch教程:Spring Data方式

Spring Boot与Elasticsearch的集成是许多开发者需要掌握的技能。本文将详细介绍如何在Spring Boot项目中集成Elasticsearch,包括Elasticsearch的简介、安装说明以及具体的集成步骤。

一、前言

网上关于Spring Boot集成Elasticsearch的文章很多,但随着Spring Boot和Elasticsearch版本的不断升级,绝大多数文章使用的集成方式和调用的方法已经过时,几乎找不到能真正适用最新Spring Boot版本和最新Elasticsearch版本的文章。本文正是基于最新Spring Boot版本和最新Elasticsearch版本实现了集成。

二、Elasticsearch 是什么?

Elasticsearch(ES)是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java语言开发的,并作为Apache许可条款下的开放源码发布,是一种流行的企业级搜索引擎。Elasticsearch用于云计算中,能够达到实时搜索、稳定、可靠、快速、安装使用方便。官方客户端在Java、.NET(C#)、PHP、Python、Apache Groovy、Ruby和许多其他语言中都是可用的。根据DB-Engines的排名显示,Elasticsearch是受欢迎的企业搜索引擎,其次是Apache Solr,也是基于Lucene。

三、Elasticsearch 安装

见CentOS7和8下安装Elasticsearch和ElasticSearch ik分词器的安装使用。

四、Spring Boot 集成 Elasticsearch 的方式

1. TransportClient

TransportClient在Elasticsearch 7.0.0中已被弃用,取而代之的是Java High Level REST Client,并将在Elasticsearch 8.0中删除。在项目中不再建议使用,详见官方链接:https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-api.html#java-api

2. Java REST Client

Java REST Client在Elasticsearch 7.15.0中已弃用,取而代之的是Java API Client。在项目中不再建议使用,详见官方链接:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/index.html

3. Java API Client

官方推荐使用的方式。详见官方链接:https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/current/index.html

4. Spring Data Elasticsearch

Spring Data Elasticsearch项目提供了与Elasticsearch搜索引擎的集成。Spring Data Elasticsearch的关键功能领域是一个以POJO为中心的模型,用于与Elastichsearch文档进行交互,并轻松编写存储库数据访问层。本文正是基于Spring Data Elasticsearch方式实现Spring Boot集成Elasticsearch。

五、创建项目集成 Elasticsearch

1. 项目说明

新建Spring Initializr项目es,项目下新建controller、entity、dao、service、impl类,实现对Elasticsearch的CRUD操作。项目目录结构如下:

2. 创建 Spring Initializr 项目 es

(1). 添加依赖

添加依赖,如果已按截图操作,pom.xml的内容会自动生成:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.4</version>
<relativePath/>
</parent>
<groupId>com.chaoyue</groupId>
<artifactId>es</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>es</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>

(2). 添加配置

application.yml文件中添加如下配置:

server:
port: 8080
spring:
elasticsearch:
uris: 192.168.1.38:9200

(3). 新建实体类 User

为减少不必要的代码,引入lombok依赖:

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
</dependency>

实体类代码如下:

package com.chaoyue.es.entity;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import java.io.Serializable;
@Data
@Document(indexName = "user")
public class User implements Serializable {
@Id
private String id; // id
private String username; // 用户名
private String password; // 密码
}

(4). 新建 dao 接口类 UserRepository

package com.chaoyue.es.dao;
import com.chaoyue.es.entity.User;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends ElasticsearchRepository<User, String> {
}

(5). 新建服务接口类 UserService

package com.chaoyue.es.service;
import com.chaoyue.es.entity.User;
public interface UserService {
User save(User user);
void delete(User user);
Iterable<User> getAll();
}

(6). 新建服务实现类 UserServiceImpl

package com.chaoyue.es.service.impl;
import com.chaoyue.es.dao.UserRepository;
import com.chaoyue.es.entity.User;
import com.chaoyue.es.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
public User save(User user) {
return userRepository.save(user);
}
@Override
public void delete(User user) {
userRepository.delete(user);
}
@Override
public Iterable<User> getAll() {
return userRepository.findAll();
}
}

(7). 新建控制类 UserController

package com.chaoyue.es.controller;
import com.chaoyue.es.entity.User;
import com.chaoyue.es.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/insert")
public String insert() {
User user = new User();
user.setId("1");
user.setUsername("张三");
user.setPassword("zhangsan");
userService.save(user);
return getAll();
}
@RequestMapping("/delete")
public String delete() {
User user = new User();
user.setId("1");
userService.delete(user);
return getAll();
}
@RequestMapping("/getAll")
public String getAll() {
List<User> list = new ArrayList<>();
Iterable<User> iterable = userService.getAll();
iterable.forEach(e->list.add((User) e));
return list.toString();
}
}

3. 启动服务并测试

启动服务后,浏览器输入:http://localhost:8080/user/insert,会新增一条id为“1”的记录:

浏览器输入:http://localhost:8080/user/delete,会删除一条id为“1”的记录:

浏览器输入:http://localhost:8080/user/getAll,会显示所有记录:

© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号