Springboot和Es整合

embedded/2025/1/15 18:28:06/

说明:本文章主要是简单整合和简单增删改查。

1.pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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.0 http://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.2.2.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>org.example</groupId><artifactId>EsDemo</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.10</version></dependency><!-- swagger --><dependency><groupId>com.github.xiaoymin</groupId><artifactId>knife4j-spring-boot-starter</artifactId><version>2.0.9</version></dependency><dependency><groupId>commons-lang</groupId><artifactId>commons-lang</artifactId><version>2.6</version></dependency></dependencies></project>

2.application.yml

spring:elasticsearch:rest:uris: http://192.168.18.154:9200

3.App.java

package org.example;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class App {public static void main(String[] args) {SpringApplication.run(App.class, args);}
}

4.SwaggerConfig.java

package org.example.config;import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;import java.util.ArrayList;
import java.util.List;/*** @author 李庆伟*/
@ConditionalOnWebApplication
@Configuration
@EnableSwagger2WebMvc
@EnableKnife4j
public class SwaggerConfig {/*** Swagger2的配置文件,这里可以配置Swagger2的一些基本的内容,比如扫描的包等等* []* @return {@link Docket}* @throws* @author 李庆伟*/@Beanpublic Docket createRestApi() {//设置请求在父类方法中,如果在本类方法中设置请求头,则覆盖父类方法List<Parameter> pars = makeHeader();return new Docket(DocumentationType.SWAGGER_2).select()//多包扫描.apis(RequestHandlerSelectors.basePackage(makeScanOne()))//.or(RequestHandlerSelectors.basePackage(makeScanTwo()))//.or(RequestHandlerSelectors.basePackage(makeScanThree())))//.apis(RequestHandlerSelectors.basePackage(App8300.class.getPackage().getName())).build().globalOperationParameters(pars).apiInfo(apiInfo());}/*** swagger封装请求头* [pars]* @return {@link List< Parameter>}* @throws* @author 李庆伟*/public List<Parameter> makeHeader(){List<Parameter> pars = new ArrayList<>();ParameterBuilder token = new ParameterBuilder();token.name("Authorization").description("Authorization").modelRef(new ModelRef("string")).parameterType("header").required(false).build();pars.add(token.build());ParameterBuilder languageCode = new ParameterBuilder();languageCode.name("languageCode").description("languageCode").modelRef(new ModelRef("string")).parameterType("header").required(false).build();pars.add(languageCode.build());return pars;}public String makeScanOne(){return "org.example.controller";}/*** 构建API文档的详细信息函数* @return*/public ApiInfo apiInfo() {return new ApiInfoBuilder().title(makeApiName()).version("1.0").build();}public String makeApiName(){return "文档服务接口-API";}}

5.EsBook.java

package org.example.entity;import lombok.Data;
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;import java.util.Date;@Data
@Document(indexName = "es_book_index",type = "xiyouji")
//indexName相当于数据库   type相当于表  实体属性相当于表的字段
public class EsBook {@Idprivate String id;//章节@Field(store = true, type = FieldType.Keyword)private String title;//章节名称@Field(store = true, type = FieldType.Keyword)private String code;//章节编码}

6.IndexController.java

package org.example.controller;import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.example.entity.EsBook;
import org.example.service.IndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import java.util.List;@RestController
@RequestMapping("/index")
@Api(value = "索引_相当于数据库", tags = "索引_相当于数据库")
public class IndexController {@Autowiredprivate IndexService indexService;/*** 添加* @return {@link }* @throws* @author* @date*/@PostMapping(value = "/add")@ApiOperation(value = "添加", notes = "添加", produces = "application/json")public String add(EsBook esBook) {indexService.add(esBook);return "ok";}/*** 修改* @return {@link }* @throws* @author* @date*/@PostMapping(value = "/update")@ApiOperation(value = "修改", notes = "修改", produces = "application/json")public String update(EsBook esBook) {indexService.update(esBook);return "ok";}/*** 查询* @return {@link }* @throws* @author* @date*/@PostMapping(value = "/query")@ApiOperation(value = "查询", notes = "查询", produces = "application/json")public List<EsBook> findQuery(EsBook esBook) {List<EsBook> list = indexService.findListByQuery(esBook);return list;}/*** 分页* @return {@link }* @throws* @author* @date*/@PostMapping(value = "/findByPage")@ApiOperation(value = "分页查询", notes = "分页查询", produces = "application/json")public Page<EsBook> findByPage(@ApiParam(required = true, value = "pageNo") @RequestParam(value = "pageNo", required = true) Integer pageNo,@ApiParam(required = true, value = "pageSize") @RequestParam(value = "pageSize", required = true) Integer pageSize,@ApiParam(required = false, value = "title") @RequestParam(value = "title", required = false) String title) {Page<EsBook> list = indexService.findByPage(pageNo, pageSize, title);return list;}/*** 详情* @return {@link }* @throws* @author* @date*/@PostMapping(value = "/show")@ApiOperation(value = "详情", notes = "详情", produces = "application/json")public EsBook show(@ApiParam(required = true, value = "章节名称") @RequestParam(value = "id", required = true) String id) {EsBook es = indexService.get(id);return es;}/*** 删除* @return {@link }* @throws* @author* @date*/@PostMapping(value = "/delete")@ApiOperation(value = "删除", notes = "删除", produces = "application/json")public String delete(@ApiParam(required = true, value = "章节名称") @RequestParam(value = "id", required = true) String id) {indexService.delete(id);return "ok";}}

7.IndexService.java

package org.example.service;import org.example.entity.EsBook;
import org.springframework.data.domain.Page;import java.util.List;public interface IndexService {void add(EsBook esBook);void delete(String id);void update(EsBook esBook);List<EsBook> findListByQuery(EsBook esBook);EsBook get(String id);Page<EsBook> findByPage(Integer pageNo, Integer pageSize, String title);
}

8.IndexServiceImpl.java

package org.example.service.impl;import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.example.entity.EsBook;
import org.example.mapper.EsBookMapper;
import org.example.service.IndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;@Service
public class IndexServiceImpl implements IndexService {@Autowiredprivate EsBookMapper esBookMapper;@Overridepublic void add(EsBook esBook) {esBook.setId(UUID.randomUUID().toString().replace("-", ""));esBookMapper.save(esBook);}@Overridepublic void update(EsBook esBook) {esBookMapper.save(esBook);}@Overridepublic List<EsBook> findListByQuery(EsBook esBook) {List<EsBook> list = new ArrayList<>();BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();queryBuilder.must(QueryBuilders.termQuery("title", esBook.getTitle()));Iterable<EsBook> it = esBookMapper.search(queryBuilder);it.forEach(e->list.add(e));return list;}@Overridepublic EsBook get(String id) {try {return esBookMapper.findById(id).get();} catch (Exception e) {e.printStackTrace();}return null;}@Overridepublic Page<EsBook> findByPage(Integer pageNo, Integer pageSize, String title) {SearchQuery searchQuery = new NativeSearchQueryBuilder()// .withQuery(QueryBuilders.matchPhraseQuery("name", kw)).withPageable(PageRequest.of(pageNo, pageSize)).build();return esBookMapper.search(searchQuery);}@Overridepublic void delete(String id) {EsBook esBook = new EsBook();esBook.setId(id);esBookMapper.delete(esBook);}}

9.EsBookMapper.java

package org.example.mapper;import org.example.entity.EsBook;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;public interface EsBookMapper extends ElasticsearchRepository<EsBook,String> {}

总结一下,记录一点点。。。。。。。。。。。。。。


http://www.ppmy.cn/embedded/154160.html

相关文章

PySide6的资源文件(.qrc 文件)简介以及RCC工具

.qrc 文件 .qrc 文件是 Qt 资源系统&#xff08;Qt Resource System&#xff09;的一部分&#xff0c;用于定义应用程序的资源集合。这些资源可以是图像、图标、样式表、音频文件等。 .qrc 文件的格式 .qrc 文件使用 XML 格式编写&#xff0c;下面将详细介绍 .qrc 文件的…

Unocss 中 !important 的使用及相关特性解析

​ 引言 在前端开发中&#xff0c;样式冲突是经常会遇到的问题。Unocss 作为一款强大的原子化 CSS 框架&#xff0c;提供了许多便捷的方式来处理样式&#xff0c;其中 !important 的使用有着独特的规则和场景。本文将深入探讨这些内容&#xff0c;并介绍一些其他有用的 Unocss …

【后端面试总结】tls中.crt和.key的关系

tls中.crt和.key的关系 引言 在现代网络通信中&#xff0c;特别是基于SSL/TLS协议的加密通信中&#xff0c;.crt和.key文件扮演着至关重要的角色。这两个文件分别代表了数字证书和私钥&#xff0c;是确保通信双方身份认证和数据传输安全性的基石。本文旨在深入探讨TLS中.crt和…

打桩机:灾害救援中的 “应急尖兵”,稳固支撑的保障|鼎跃安全

在自然灾害或突发事故中&#xff0c;如地震、泥石流、洪涝灾害、山体滑坡等&#xff0c;地质条件的不稳定可能导致建筑物倒塌、道路损毁、堤坝决口等情况&#xff0c;严重威胁人员和财产安全。 打桩机是一种用于将桩打入地基的重型机械设备&#xff0c;其主要功能是提供支撑力&…

k8s基础(6)—Kubernetes-存储

Kubernetes-存储概述 k8s的持久券简介 Kubernetes的持久卷&#xff08;PersistentVolume, PV&#xff09;和持久卷声明&#xff08;PersistentVolumeClaim, PVC&#xff09;为用户在Kubernetes中使用卷提供了抽象。PV是集群中的一块存储&#xff0c;PVC是对这部分存储的请求。…

单元测试流程

1.如何编写测试 odoo 的后端测试使用的是unittest,只需要在模块文件下增加一个test的目录即可,注意该test目录不需要被模块文件里的_init_.py文件导入,然后就是使用unittest的框架方式写测试用例 2.启动单元测试 首先建立一个新的数据库并且选择加载演示数据(demo data) 然后…

Centos9-SSH免密登录配置-修改22端口-关闭密码登录-提高安全性

Centos9-SSH免密登录配置-修改22端口-关闭密码登录 生成秘钥对将公钥信息存进authorized_keys测试登录查询访问记录、比对指纹更换22访问端口关闭账号密码登录 生成秘钥对 生成密钥对&#xff0c;指定 备注 和 文件目录命令执行后&#xff0c;默认两次回车&#xff0c;不设置秘…

服务器数据恢复—raid5故障导致上层ORACLE无法启动的数据恢复案例

服务器数据恢复环境&故障&#xff1a; 一台服务器上的8块硬盘组建了一组raid5磁盘阵列。上层安装windows server操作系统&#xff0c;部署了oracle数据库。 raid5阵列中有2块硬盘的硬盘指示灯显示异常报警。服务器操作系统无法启动&#xff0c;ORACLE数据库也无法启动。 服…