IT评测·应用市场-qidao123.com

标题: Springboot和Es整合 [打印本页]

作者: 温锦文欧普厨电及净水器总代理    时间: 2025-1-15 10:56
标题: Springboot和Es整合
阐明:本文章重要是简单整合和简单增删改查。

1.pom.xml
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3.          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5.     <modelVersion>4.0.0</modelVersion>
  6.     <parent>
  7.         <groupId>org.springframework.boot</groupId>
  8.         <artifactId>spring-boot-starter-parent</artifactId>
  9.         <version>2.2.2.RELEASE</version>
  10.         <relativePath/> <!-- lookup parent from repository -->
  11.     </parent>
  12.     <groupId>org.example</groupId>
  13.     <artifactId>EsDemo</artifactId>
  14.     <version>1.0-SNAPSHOT</version>
  15.     <properties>
  16.         <maven.compiler.source>8</maven.compiler.source>
  17.         <maven.compiler.target>8</maven.compiler.target>
  18.         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  19.     </properties>
  20.     <dependencies>
  21.         <dependency>
  22.             <groupId>org.springframework.boot</groupId>
  23.             <artifactId>spring-boot-starter-web</artifactId>
  24.         </dependency>
  25.         <dependency>
  26.             <groupId>org.springframework.boot</groupId>
  27.             <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
  28.         </dependency>
  29.         <dependency>
  30.             <groupId>org.projectlombok</groupId>
  31.             <artifactId>lombok</artifactId>
  32.             <version>1.18.10</version>
  33.         </dependency>
  34.         <!-- swagger -->
  35.         <dependency>
  36.             <groupId>com.github.xiaoymin</groupId>
  37.             <artifactId>knife4j-spring-boot-starter</artifactId>
  38.             <version>2.0.9</version>
  39.         </dependency>
  40.         <dependency>
  41.             <groupId>commons-lang</groupId>
  42.             <artifactId>commons-lang</artifactId>
  43.             <version>2.6</version>
  44.         </dependency>
  45.     </dependencies>
  46. </project>
复制代码
2.application.yml
  1. spring:
  2.   elasticsearch:
  3.     rest:
  4.       uris: http://192.168.18.154:9200
复制代码
3.App.java
  1. package org.example;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class App {
  6.     public static void main(String[] args) {
  7.         SpringApplication.run(App.class, args);
  8.     }
  9. }
复制代码
4.SwaggerConfig.java
  1. package org.example.config;
  2. import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
  3. import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. import springfox.documentation.builders.ApiInfoBuilder;
  7. import springfox.documentation.builders.ParameterBuilder;
  8. import springfox.documentation.builders.RequestHandlerSelectors;
  9. import springfox.documentation.schema.ModelRef;
  10. import springfox.documentation.service.ApiInfo;
  11. import springfox.documentation.service.Parameter;
  12. import springfox.documentation.spi.DocumentationType;
  13. import springfox.documentation.spring.web.plugins.Docket;
  14. import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;
  15. import java.util.ArrayList;
  16. import java.util.List;
  17. /**
  18. * @author 李庆伟
  19. */
  20. @ConditionalOnWebApplication
  21. @Configuration
  22. @EnableSwagger2WebMvc
  23. @EnableKnife4j
  24. public class SwaggerConfig {
  25.     /**
  26.      * Swagger2的配置文件,这里可以配置Swagger2的一些基本的内容,比如扫描的包等等
  27.      * []
  28.      * @return {@link Docket}
  29.      * @throws
  30.      * @author 李庆伟
  31.      */
  32.     @Bean
  33.     public Docket createRestApi() {
  34.         //设置请求在父类方法中,如果在本类方法中设置请求头,则覆盖父类方法
  35.         List<Parameter> pars = makeHeader();
  36.         return new Docket(DocumentationType.SWAGGER_2)
  37.                 .select()
  38.                 //多包扫描
  39.                 .apis(RequestHandlerSelectors.basePackage(makeScanOne()))
  40.                         //.or(RequestHandlerSelectors.basePackage(makeScanTwo()))
  41.                         //.or(RequestHandlerSelectors.basePackage(makeScanThree())))
  42.                 //.apis(RequestHandlerSelectors.basePackage(App8300.class.getPackage().getName()))
  43.                 .build()
  44.                 .globalOperationParameters(pars)
  45.                 .apiInfo(apiInfo());
  46.     }
  47.     /**
  48.      * swagger封装请求头
  49.      * [pars]
  50.      * @return {@link List< Parameter>}
  51.      * @throws
  52.      * @author 李庆伟
  53.      */
  54.     public List<Parameter> makeHeader(){
  55.         List<Parameter> pars = new ArrayList<>();
  56.         ParameterBuilder token = new ParameterBuilder();
  57.         token.name("Authorization").description("Authorization")
  58.                 .modelRef(new ModelRef("string"))
  59.                 .parameterType("header")
  60.                 .required(false).build();
  61.         pars.add(token.build());
  62.         ParameterBuilder languageCode = new ParameterBuilder();
  63.         languageCode.name("languageCode").description("languageCode")
  64.                 .modelRef(new ModelRef("string"))
  65.                 .parameterType("header")
  66.                 .required(false).build();
  67.         pars.add(languageCode.build());
  68.         return pars;
  69.     }
  70.     public String makeScanOne(){
  71.         return "org.example.controller";
  72.     }
  73.     /**
  74.      * 构建API文档的详细信息函数
  75.      * @return
  76.      */
  77.     public ApiInfo apiInfo() {
  78.         return new ApiInfoBuilder()
  79.                 .title(makeApiName())
  80.                 .version("1.0")
  81.                 .build();
  82.     }
  83.     public String makeApiName(){
  84.         return "文档服务接口-API";
  85.     }
  86. }
复制代码
5.EsBook.java
  1. package org.example.entity;
  2. import lombok.Data;
  3. import org.springframework.data.annotation.Id;
  4. import org.springframework.data.elasticsearch.annotations.Document;
  5. import org.springframework.data.elasticsearch.annotations.Field;
  6. import org.springframework.data.elasticsearch.annotations.FieldType;
  7. import java.util.Date;
  8. @Data
  9. @Document(indexName = "es_book_index",type = "xiyouji")
  10. //indexName相当于数据库   type相当于表  实体属性相当于表的字段
  11. public class EsBook {
  12.     @Id
  13.     private String id;//章节
  14.     @Field(store = true, type = FieldType.Keyword)
  15.     private String title;//章节名称
  16.     @Field(store = true, type = FieldType.Keyword)
  17.     private String code;//章节编码
  18. }
复制代码
6.IndexController.java
  1. package org.example.controller;
  2. import io.swagger.annotations.Api;
  3. import io.swagger.annotations.ApiOperation;
  4. import io.swagger.annotations.ApiParam;
  5. import org.example.entity.EsBook;
  6. import org.example.service.IndexService;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.data.domain.Page;
  9. import org.springframework.web.bind.annotation.PostMapping;
  10. import org.springframework.web.bind.annotation.RequestMapping;
  11. import org.springframework.web.bind.annotation.RequestParam;
  12. import org.springframework.web.bind.annotation.RestController;
  13. import java.util.List;
  14. @RestController
  15. @RequestMapping("/index")
  16. @Api(value = "索引_相当于数据库", tags = "索引_相当于数据库")
  17. public class IndexController {
  18.     @Autowired
  19.     private IndexService indexService;
  20.     /**
  21.      * 添加
  22.      * @return {@link }
  23.      * @throws
  24.      * @author
  25.      * @date
  26.      */
  27.     @PostMapping(value = "/add")
  28.     @ApiOperation(value = "添加", notes = "添加", produces = "application/json")
  29.     public String add(EsBook esBook) {
  30.         indexService.add(esBook);
  31.         return "ok";
  32.     }
  33.     /**
  34.      * 修改
  35.      * @return {@link }
  36.      * @throws
  37.      * @author
  38.      * @date
  39.      */
  40.     @PostMapping(value = "/update")
  41.     @ApiOperation(value = "修改", notes = "修改", produces = "application/json")
  42.     public String update(EsBook esBook) {
  43.         indexService.update(esBook);
  44.         return "ok";
  45.     }
  46.     /**
  47.      * 查询
  48.      * @return {@link }
  49.      * @throws
  50.      * @author
  51.      * @date
  52.      */
  53.     @PostMapping(value = "/query")
  54.     @ApiOperation(value = "查询", notes = "查询", produces = "application/json")
  55.     public List<EsBook> findQuery(EsBook esBook) {
  56.         List<EsBook> list = indexService.findListByQuery(esBook);
  57.         return list;
  58.     }
  59.     /**
  60.      * 分页
  61.      * @return {@link }
  62.      * @throws
  63.      * @author
  64.      * @date
  65.      */
  66.     @PostMapping(value = "/findByPage")
  67.     @ApiOperation(value = "分页查询", notes = "分页查询", produces = "application/json")
  68.     public Page<EsBook> findByPage(@ApiParam(required = true, value = "pageNo") @RequestParam(value = "pageNo", required = true) Integer pageNo,
  69.                                    @ApiParam(required = true, value = "pageSize") @RequestParam(value = "pageSize", required = true) Integer pageSize,
  70.                                    @ApiParam(required = false, value = "title") @RequestParam(value = "title", required = false) String title) {
  71.         Page<EsBook> list = indexService.findByPage(pageNo, pageSize, title);
  72.         return list;
  73.     }
  74.     /**
  75.      * 详情
  76.      * @return {@link }
  77.      * @throws
  78.      * @author
  79.      * @date
  80.      */
  81.     @PostMapping(value = "/show")
  82.     @ApiOperation(value = "详情", notes = "详情", produces = "application/json")
  83.     public EsBook show(@ApiParam(required = true, value = "章节名称") @RequestParam(value = "id", required = true) String id) {
  84.         EsBook es = indexService.get(id);
  85.         return es;
  86.     }
  87.     /**
  88.      * 删除
  89.      * @return {@link }
  90.      * @throws
  91.      * @author
  92.      * @date
  93.      */
  94.     @PostMapping(value = "/delete")
  95.     @ApiOperation(value = "删除", notes = "删除", produces = "application/json")
  96.     public String delete(@ApiParam(required = true, value = "章节名称") @RequestParam(value = "id", required = true) String id) {
  97.         indexService.delete(id);
  98.         return "ok";
  99.     }
  100. }
复制代码
7.IndexService.java
  1. package org.example.service;
  2. import org.example.entity.EsBook;
  3. import org.springframework.data.domain.Page;
  4. import java.util.List;
  5. public interface IndexService {
  6.     void add(EsBook esBook);
  7.     void delete(String id);
  8.     void update(EsBook esBook);
  9.     List<EsBook> findListByQuery(EsBook esBook);
  10.     EsBook get(String id);
  11.     Page<EsBook> findByPage(Integer pageNo, Integer pageSize, String title);
  12. }
复制代码
8.IndexServiceImpl.java
  1. package org.example.service.impl;
  2. import org.elasticsearch.index.query.BoolQueryBuilder;
  3. import org.elasticsearch.index.query.QueryBuilders;
  4. import org.example.entity.EsBook;
  5. import org.example.mapper.EsBookMapper;
  6. import org.example.service.IndexService;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.data.domain.Page;
  9. import org.springframework.data.domain.PageRequest;
  10. import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
  11. import org.springframework.data.elasticsearch.core.query.SearchQuery;
  12. import org.springframework.stereotype.Service;
  13. import java.util.ArrayList;
  14. import java.util.Date;
  15. import java.util.List;
  16. import java.util.UUID;
  17. @Service
  18. public class IndexServiceImpl implements IndexService {
  19.     @Autowired
  20.     private EsBookMapper esBookMapper;
  21.     @Override
  22.     public void add(EsBook esBook) {
  23.         esBook.setId(UUID.randomUUID().toString().replace("-", ""));
  24.         esBookMapper.save(esBook);
  25.     }
  26.     @Override
  27.     public void update(EsBook esBook) {
  28.         esBookMapper.save(esBook);
  29.     }
  30.     @Override
  31.     public List<EsBook> findListByQuery(EsBook esBook) {
  32.         List<EsBook> list = new ArrayList<>();
  33.         BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
  34.         queryBuilder.must(QueryBuilders.termQuery("title", esBook.getTitle()));
  35.         Iterable<EsBook> it = esBookMapper.search(queryBuilder);
  36.         it.forEach(e->list.add(e));
  37.         return list;
  38.     }
  39.     @Override
  40.     public EsBook get(String id) {
  41.         try {
  42.             return esBookMapper.findById(id).get();
  43.         } catch (Exception e) {
  44.             e.printStackTrace();
  45.         }
  46.         return null;
  47.     }
  48.     @Override
  49.     public Page<EsBook> findByPage(Integer pageNo, Integer pageSize, String title) {
  50.         SearchQuery searchQuery = new NativeSearchQueryBuilder()
  51.                // .withQuery(QueryBuilders.matchPhraseQuery("name", kw))
  52.                 .withPageable(PageRequest.of(pageNo, pageSize))
  53.                 .build();
  54.         return esBookMapper.search(searchQuery);
  55.     }
  56.     @Override
  57.     public void delete(String id) {
  58.         EsBook esBook = new EsBook();
  59.         esBook.setId(id);
  60.         esBookMapper.delete(esBook);
  61.     }
  62. }
复制代码
9.EsBookMapper.java
  1. package org.example.mapper;
  2. import org.example.entity.EsBook;
  3. import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
  4. public interface EsBookMapper extends ElasticsearchRepository<EsBook,String> {
  5. }
复制代码

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







免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 IT评测·应用市场-qidao123.com (https://dis.qidao123.com/) Powered by Discuz! X3.4