• ELK入门(二)- springboot整合ES


    springboot整合elasticsearch

    引用依赖

    
    <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.0modelVersion>
    
        <groupId>com.ohb.springbootgroupId>
        <artifactId>springboot-esartifactId>
        <version>1.0-SNAPSHOTversion>
    
        <properties>
            <maven.compiler.source>8maven.compiler.source>
            <maven.compiler.target>8maven.compiler.target>
            <project.knife4j.version>4.0.0project.knife4j.version>
        properties>
    
        <parent>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-parentartifactId>
            <version>2.6.13version>
        parent>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-webartifactId>
            dependency>
            
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-data-elasticsearchartifactId>
            dependency>
            
            
    
            <dependency>
                <groupId>org.projectlombokgroupId>
                <artifactId>lombokartifactId>
                <version>1.18.24version>
            dependency>
    
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-testartifactId>
                <scope>testscope>
            dependency>
    
            <dependency>
                <groupId>junitgroupId>
                <artifactId>junitartifactId>
                <version>4.12version>
                <scope>testscope>
            dependency>
        dependencies>
    
    project>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56

    配置文件(application.yml)

    spring:
      elasticsearch:
        uris: http://192.168.198.129:9200
      data:
        elasticsearch:
          repositories:
            enabled: true
    
      application:
        name: springboot-es
    server:
      port: 9070
    
    knife4j:
      enable: true
      openapi:
        title: knife4测试elasticsearch
        description: 测试接口
        email: hbo@djs.com
        concat: ohb
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    配置类

    package com.ohb.springboot.es.config;
    
    
    import org.elasticsearch.client.RestHighLevelClient;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.data.elasticsearch.client.ClientConfiguration;
    import org.springframework.data.elasticsearch.client.RestClients;
    import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;
    
    /**
     * Elasticsearch配置
     */
    public class ElasticsearchConfig extends AbstractElasticsearchConfiguration {
    
        @Value("${spring.elasticsearch.uris}")
        private String uris;
    
        @Override
        public RestHighLevelClient elasticsearchClient() {
           ClientConfiguration configuration=
                   ClientConfiguration.builder()
                           .connectedTo(uris)
                           .build();
           return RestClients.create(configuration).rest();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    文档类

    package com.ohb.springboot.es.entity;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    import org.springframework.data.annotation.Id;
    import org.springframework.data.elasticsearch.annotations.DateFormat;
    import org.springframework.data.elasticsearch.annotations.Document;
    import org.springframework.data.elasticsearch.annotations.Field;
    import org.springframework.data.elasticsearch.annotations.FieldType;
    
    import java.math.BigDecimal;
    import java.time.LocalDate;
    
    /**
     * 创建文档实体类
     */
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Document(indexName = "book_index",createIndex = true)
    public class BookDoc {
        @Id
        @Field(type = FieldType.Text)
        private String id;
    
        @Field(type = FieldType.Text)
        private String title;
    
        @Field(type = FieldType.Text)
        private String author;
    
        @Field(type = FieldType.Text)
        private String publisher;
    
        @Field(type = FieldType.Double)
        private BigDecimal price;
    
        @Field(type = FieldType.Text)
        private String content;
    
     	@Field(type = FieldType.Date,format = DateFormat.year_month_day)
        @JsonFormat(pattern = "yyyy-MM-dd",timezone = "GMT+8")
        private LocalDate publishDate;  //此处要使用LocalDate类型,否则会报转换错误
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    DTO类

    package com.ohb.springboot.es.dto;
    
    import io.swagger.annotations.ApiModel;
    import io.swagger.annotations.ApiModelProperty;
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    import java.util.Date;
    
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @ApiModel("DTO")
    public class HttpResp {
        @ApiModelProperty("DTO返回代码")
        private int code;
    
        @ApiModelProperty("DTO返回信息")
        private String msg;
    
        @ApiModelProperty("dto返回时间")
        private Date time;
    
        @ApiModelProperty("dto返回数据")
        private Object results;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    定义elasticsearch操作数据接口

    package com.ohb.springboot.es.dao;
    
    
    import com.ohb.springboot.es.entity.BookDoc;
    import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
    
    public interface IBookRepository extends ElasticsearchRepository<BookDoc,String> {
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    image-20230311112826280

    服务层接口(service)

    接口
    package com.ohb.springboot.es.service;
    import com.ohb.springboot.es.entity.BookDoc;
    
    import java.util.List;
    
    public interface IBookService {
    
        List<BookDoc> findAll();
        void addBookDoc(BookDoc bookDoc);
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    实现类
    package com.ohb.springboot.es.service.impl;
    
    import com.ohb.springboot.es.dao.IBookDocRepository;
    import com.ohb.springboot.es.entity.BookDoc;
    import com.ohb.springboot.es.service.IBookService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.ArrayList;
    import java.util.List;
    
    @Service
    public class BookServiceImpl implements IBookService {
    
        @Autowired
        private IBookDocRepository ibdr;
    
        /**
         转换为List集合
         */
        @Override
        public List<BookDoc> findAll() {
            List<BookDoc> list = new ArrayList<>();
            ibdr.findAll().forEach((bc) -> list.add(bc));
            return list;
        }
    
        @Override
        public void addBookDoc(BookDoc bookDoc) {
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    控制层(controller)

    package com.ohb.springboot.es.controller;
    
    import com.ohb.springboot.es.dto.HttpResp;
    import com.ohb.springboot.es.service.IBookService;
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiOperation;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.Date;
    @Api(tags = "图书接口类")
    @RestController
    @RequestMapping("/book/api")
    public class BookController {
    
        @Autowired
        private IBookService ibs;
    
        @ApiOperation("查询所有图书信息")
        @GetMapping("/findAllBooks")
        public HttpResp findAllBooks() {
          return new HttpResp(20001, "查询所有图书成功", new Date(), ibs.findAll());
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    测试

    package com.ohb.springboot.es.dao;
    
    import com.ohb.springboot.es.entity.Book;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    import java.math.BigDecimal;
    import java.time.LocalDate;
    
    import static org.junit.Assert.*;
    
    @SpringBootTest
    @RunWith(SpringJUnit4ClassRunner.class)
    public class IBookRepositoryTest {
    
        @Autowired
        private IBookRepository bookRepository;
    
        @Test
        public void saveBook(){
                bookRepository.save(new BookDoc("wnhz001","西游记","吴承恩","神话出版社", BigDecimal.valueOf(33.5),"历经千险,终成大道", LocalDate.now()));
        }
    
        @Test
        public void findAll(){
            bookRepository.findAll().forEach(System.out::println);
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
     .   ____          _            __ _ _
     /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
    ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
     \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
      '  |____| .__|_| |_|_| |_\__, | / / / /
     =========|_|==============|___/=/_/_/_/
     :: Spring Boot ::               (v2.6.13)
    
    2023-03-08 17:25:50.048  INFO 6936 --- [           main] c.o.s.es.dao.IBookRepositoryTest         : Starting IBookRepositoryTest using Java 1.8.0_311 on XTZJ-20220114OE with PID 6936 (started by Administrator in D:\wnhz-workspace\springboot\springboot-es)
    2023-03-08 17:25:50.053  INFO 6936 --- [           main] c.o.s.es.dao.IBookRepositoryTest         : No active profile set, falling back to 1 default profile: "default"
    2023-03-08 17:25:51.683  INFO 6936 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data Elasticsearch repositories in DEFAULT mode.
    2023-03-08 17:25:51.824  INFO 6936 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 128 ms. Found 1 Elasticsearch repository interfaces.
    2023-03-08 17:25:51.840  INFO 6936 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data Reactive Elasticsearch repositories in DEFAULT mode.
    2023-03-08 17:25:51.847  INFO 6936 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 6 ms. Found 0 Reactive Elasticsearch repository interfaces.
    2023-03-08 17:25:58.622  WARN 6936 --- [/O dispatcher 1] org.elasticsearch.client.RestClient      : request [GET http://192.168.198.129:9200/] returned 1 warnings: [299 Elasticsearch-7.17.7-78dcaaa8cee33438b91eca7f5c7f56a70fec9e80 "Elasticsearch built-in security features are not enabled. Without authentication, your cluster could be accessible to anyone. See https://www.elastic.co/guide/en/elasticsearch/reference/7.17/security-minimal-setup.html to enable security."]
    2023-03-08 17:25:58.910  WARN 6936 --- [           main] org.elasticsearch.client.RestClient      : request [HEAD http://192.168.198.129:9200/book_index?ignore_throttled=false&ignore_unavailable=false&expand_wildcards=open%2Cclosed&allow_no_indices=false] returned 2 warnings: [299 Elasticsearch-7.17.7-78dcaaa8cee33438b91eca7f5c7f56a70fec9e80 "Elasticsearch built-in security features are not enabled. Without authentication, your cluster could be accessible to anyone. See https://www.elastic.co/guide/en/elasticsearch/reference/7.17/security-minimal-setup.html to enable security."],[299 Elasticsearch-7.17.7-78dcaaa8cee33438b91eca7f5c7f56a70fec9e80 "[ignore_throttled] parameter is deprecated because frozen indices have been deprecated. Consider cold or frozen tiers in place of frozen indices."]
    2023-03-08 17:25:59.096  INFO 6936 --- [           main] c.o.s.es.dao.IBookRepositoryTest         : Started IBookRepositoryTest in 10.118 seconds (JVM running for 13.203)
    2023-03-08 17:25:59.977  WARN 6936 --- [           main] org.elasticsearch.client.RestClient      : request [POST http://192.168.198.129:9200/book_index/_search?typed_keys=true&max_concurrent_shard_requests=5&ignore_unavailable=false&expand_wildcards=open&allow_no_indices=true&ignore_throttled=true&search_type=query_then_fetch&batched_reduce_size=512] returned 2 warnings: [299 Elasticsearch-7.17.7-78dcaaa8cee33438b91eca7f5c7f56a70fec9e80 "Elasticsearch built-in security features are not enabled. Without authentication, your cluster could be accessible to anyone. See https://www.elastic.co/guide/en/elasticsearch/reference/7.17/security-minimal-setup.html to enable security."],[299 Elasticsearch-7.17.7-78dcaaa8cee33438b91eca7f5c7f56a70fec9e80 "[ignore_throttled] parameter is deprecated because frozen indices have been deprecated. Consider cold or frozen tiers in place of frozen indices."]
    2023-03-08 17:26:00.235  WARN 6936 --- [           main] org.elasticsearch.client.RestClient      : request [POST http://192.168.198.129:9200/book_index/_search?typed_keys=true&max_concurrent_shard_requests=5&ignore_unavailable=false&expand_wildcards=open&allow_no_indices=true&ignore_throttled=true&search_type=query_then_fetch&batched_reduce_size=512] returned 2 warnings: [299 Elasticsearch-7.17.7-78dcaaa8cee33438b91eca7f5c7f56a70fec9e80 "Elasticsearch built-in security features are not enabled. Without authentication, your cluster could be accessible to anyone. See https://www.elastic.co/guide/en/elasticsearch/reference/7.17/security-minimal-setup.html to enable security."],[299 Elasticsearch-7.17.7-78dcaaa8cee33438b91eca7f5c7f56a70fec9e80 "[ignore_throttled] parameter is deprecated because frozen indices have been deprecated. Consider cold or frozen tiers in place of frozen indices."]
    
    
    Book(id=wnhz001, title=西游记, author=吴承恩, publisher=神话出版社, price=33.5, content=历经千险,终成大道, publishDate=Wed Mar 08 17:25:39 CST 2023)
    
    Process finished with exit code 0
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    image-20230308173855180

    • knife4测试

    image-20230311122456638

  • 相关阅读:
    volatile 关键字有什么用?它的实现原理是什么?
    Docker consul的容器服务更新与发现
    SpringBoot高校宿舍管理系统
    【Hack The Box】linux练习-- Pit
    实现艾尔登法环中的大卢恩效果
    iview踩坑日记(一)——DatePicker
    ROS2——初识ROS2(一)
    并行计算总结
    35岁了,月薪还不足2W,辞职又怕找不到工作,该何去何从?
    springMvc整合swagger
  • 原文地址:https://blog.csdn.net/qq_36115196/article/details/136196062