IDEA搭建SpringBoot+Elasticsearch6.8完整流程
一、环境版本说明兼容不踩坑组件推荐版本SpringBoot2.2.13Elasticsearch6.8.23Spring Data Elasticsearch随 Boot 版本自动匹配JDK1.8IDEA2022二、IDEA 手动创建 SpringBoot 项目1. 新建空 Maven 项目File → New → Project → 选择MavenJDK 选 1.8/11下一步填写 Group、Artifact微服务模块名如es-service完成创建删除src以外多余文件手动补全 SpringBoot 结构2. pom.xml 引入核心依赖?xml version1.0 encodingUTF-8? project xmlnshttp://maven.apache.org/POM/4.0.0 xmlns:xsihttp://www.w3.org/2001/XMLSchema-instance xsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd modelVersion4.0.0/modelVersion !-- 父工程SpringBoot -- parent groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-parent/artifactId version2.2.13.RELEASE/version relativePath/ /parent groupIdorg.example/groupId artifactIdElasticsearch-demo-service/artifactId version1.0-SNAPSHOT/version namees-service/name properties maven.compiler.source8/maven.compiler.source maven.compiler.target8/maven.compiler.target project.build.sourceEncodingUTF-8/project.build.sourceEncoding !-- 与 ES 6.8.23 服务端版本对齐 -- elasticsearch.version6.8.23/elasticsearch.version /properties dependencies !-- SpringBoot Web 微服务基础 -- dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-web/artifactId /dependency !-- SpringData Elasticsearch 核心依赖 -- dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-data-elasticsearch/artifactId /dependency !-- ES 6.8 REST 客户端版本由 elasticsearch.version 统一管理 -- dependency groupIdorg.elasticsearch.client/groupId artifactIdelasticsearch-rest-high-level-client/artifactId /dependency !-- lombok简化实体类 -- dependency groupIdorg.projectlombok/groupId artifactIdlombok/artifactId optionaltrue/optional /dependency !-- 测试 -- dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-test/artifactId scopetest/scope /dependency /dependencies build plugins plugin groupIdorg.springframework.boot/groupId artifactIdspring-boot-maven-plugin/artifactId configuration excludes exclude goupidorg.projectlombok/goupid artifactIdlombok/artifactId /exclude /excludes /configuration /plugin /plugins /build /project刷新 Maven等待依赖下载完成。三、项目目录手动创建标准微服务分层四、配置文件 application.yml ES 连接server: port: 8081 # 微服务端口避免冲突 spring: elasticsearch: rest: # ES 6.8 REST 地址多个节点逗号分隔 uris: http://192.168.1.4:9200 # 无账号密码留空有认证填写 username: password: connection-timeout: 10s read-timeout: 30s五、编写启动类 EsServiceApplication.javaSpringBootApplication(exclude { RestClientAutoConfiguration.class, ElasticsearchDataAutoConfiguration.class }) EnableElasticsearchRepositories(basePackages com.es.repository) public class EsServiceApplication { public static void main(String[] args) { SpringApplication.run(EsServiceApplication.class,args); } }六、ES 文档实体类 UserDoc对应 ES 索引注解Document、Id、Fieldpackage com.es.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; 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; // indexNameES索引名typeES6.x 必填createIndex true 项目启动自动创建索引 Document(indexName user_info, type doc, createIndex true) Data NoArgsConstructor AllArgsConstructor public class UserDoc { // ES文档唯一ID Id private Long id; // type字段类型text支持分词keyword不分词 Field(type FieldType.Text, analyzer ik_max_word) private String username; Field(type FieldType.Keyword) private String phone; Field(type FieldType.Integer) private Integer age; Field(type FieldType.Text, analyzer ik_max_word) private String address; }分词器 ik 需要提前在 ES 安装 ik 分词插件否则去掉analyzer属性。七、Repository 持久层SpringDataES类似 MybatisPlus无需写 SQL内置 CRUD、分页、条件查询Repository public interface UserRepository extends ElasticsearchRepositoryUserDoc, Long { // 自定义根据用户名模糊分页查询方法名自动解析查询 PageUserDoc findByUsernameLike(String username, Pageable pageable); }八、业务层 Service1. UserService 接口public interface UserService { // 新增/更新文档 void saveUser(UserDoc userDoc); // 根据ID查询 UserDoc getUserById(Long id); // 根据ID删除 void deleteUser(Long id); // 分页模糊查询用户名 PageUserDoc searchUser(String keyword, Integer pageNum, Integer pageSize); }2. UserServiceImpl 实现类package com.es.service.impl; import com.es.entity.UserDoc; import com.es.repository.UserRepository; import com.es.service.UserService; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import javax.annotation.Resource; Service public class UserServiceImpl implements UserService { Resource private UserRepository userRepository; Override public void saveUser(UserDoc userDoc) { userRepository.save(userDoc); } Override public UserDoc getUserById(Long id) { return userRepository.findById(id).orElse(null); } Override public void deleteUser(Long id) { userRepository.deleteById(id); } Override public PageUserDoc searchUser(String keyword, Integer pageNum, Integer pageSize) { // ES分页页码从0开始 Pageable pageable PageRequest.of(pageNum - 1, pageSize); return userRepository.findByUsernameLike(keyword, pageable); } }九、Controller 对外微服务接口package com.es.controller; import com.es.entity.UserDoc; import com.es.service.UserService; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; RestController RequestMapping(/es/user) public class EsController { Resource private UserService userService; // 新增/修改 PostMapping(/save) public String save(RequestBody UserDoc userDoc) { userService.saveUser(userDoc); return 操作成功; } // 根据id查询 GetMapping(/{id}) public UserDoc get(PathVariable Long id) { return userService.getUserById(id); } // 删除 DeleteMapping(/{id}) public String delete(PathVariable Long id) { userService.deleteUser(id); return 删除成功; } // 分页搜索 GetMapping(/search) public PageUserDoc search( RequestParam String keyword, RequestParam(defaultValue 1) Integer pageNum, RequestParam(defaultValue 10) Integer pageSize ) { return userService.searchUser(keyword, pageNum, pageSize); } }十、前置准备启动 Elasticsearch解压 ES6.8.23执行bin/elasticsearch启动访问http://127.0.0.1:9200 出现 json 代表启动成功关闭防火墙、跨域可选避免连接拒绝十一、启动项目测试接口1. 新增数据 POST http://localhost:8081/es/user/save请求体 JSON{ id: 1, username: 张三程序员, phone: 13800138000, age: 26, address: 北京市海淀区中关村 }2. 查询 GET http://localhost:8081/es/user/13. 模糊搜索 GET http://localhost:8081/es/user/search?keyword张三 pageNum1pageSize104. 删除 DELETE http://localhost:8081/es/user/1