ELK入门(二)- springboot整合ES

news/2024/7/7 6:00:03 标签: elk, spring boot, elasticsearch

elasticsearch_0">springboot整合elasticsearch

引用依赖

<?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>

    <groupId>com.ohb.springboot</groupId>
    <artifactId>springboot-es</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.knife4j.version>4.0.0</project.knife4j.version>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.13</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--引入elasticsearch-->
        <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.24</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

配置文件(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

配置类

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();
    }
}

文档类

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类型,否则会报转换错误
}

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;
}

elasticsearch_204">定义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> {
}

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);
}

实现类
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) {
    }
}

控制层(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());
    }
}

测试

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);
    }

}
 .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: 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

image-20230308173855180

  • knife4测试

image-20230311122456638


http://www.niftyadmin.cn/n/5384876.html

相关文章

BUUCTF crypto做题记录(7)新手向

一、Dangerous RSA 得到的密文如下 首先&#xff0c;我们对n进行大数分解看行不行。 其次&#xff0c;我们可看一下数的特征&#xff08;除了一些基础题&#xff0c;一般情况下n都是分解不了的&#xff0c;应该首先观察一下数据特征&#xff0c;我很久没做RSA了&#xff0c;有…

js filter,every,includes 过滤数组

背景&#xff1a; 页面&#xff1a;在项目中遇到的&#xff0c;前端页面显示为&#xff0c;顶部是下拉搜索条件,下面是一个表格&#xff1b; 数据&#xff1a;接口请求一次性拿到所有&#xff1a;搜索条件里的下拉选项和表格中的数据&#xff1b; 现状&#xff1a;需要前端在搜…

v-rep插件

v-rep官网插件汉化教程 官网教程 插件是什么 插件本质上就是动态库文件。 linux下是libsimXXXX.so&#xff1b; 其中XXXX是插件的名称。 请至少使用4个字符&#xff0c;并且不要使用下划线&#xff0c;因为该插件会被忽略&#xff08;但是&#xff0c;当插件本身加载一些其…

Python - 【Socket】消息粘包处理demo(二)

一. 前言 在网络编程中&#xff0c;粘包是指TCP协议在传输过程中&#xff0c;多条数据被合并成一条数据发送或者一条数据被拆分成多个数据发送的现象。 二. 粘包问题的常规处理方法&#xff1a; 使用固定长度的包头 可以在发送数据前先发送一个固定长度的包头&#xff0c;包…

MySQL学习Day19——索引的数据结构

一、为什么使用索引: 索引是存储引擎用于快速找到数据记录的一种数据结构&#xff0c;就好比一本教课书的目录部分&#xff0c;通过目录中找到对应文章的页码&#xff0c;便可快速定位到需要的文章。MySQL中也是一样的道理&#xff0c;进行数据査找时&#xff0c;首先查看查询…

EXCEL通过VBA字典的方式将各个分表的数据经过计算后显示在总表中

EXCEL通过VBA字典的方式将各个分表的数据经过计算后显示在总表中 Sub 按钮1_Click() Dim wba As Workbook Dim shta As Worksheet Dim ak(1 To 2000) As String i 1 Dim fil As Stringfil Dir(ThisWorkbook.Path & "\*.xls*")Do While fil <> "&qu…

Ansible cron模块 适用于管理计划任务 设置多个计划任务

目录 选项添加一个计划任务检查是否添加成功删除计划任务检查是否执行成功 选项 其使用的语法跟我们的crontab文件中的语法一致&#xff0c;同时&#xff0c;可以指定以下选项&#xff1a; day #日应该运行的工作( 1-31, , /2, ) hour # 小时 ( 0-23, , /2, ) minute #分钟( 0…

python3调用阿里云openapi脚本 - 生产环境

alicloud openapi 调用 - python 场景描述注意事项脚本如下场景描述 在各公司都在降本增效的前提下,可能更多的公司会选择性使用云服务器,这样相比较而言,对后续的服务器维护、产品使用来说,创造出更多便捷的方式,云服务也给我们带来了更多的便捷性,下面是从阿里云上摘抄…