Java

SpringBoot整合ElasticSearch

2023-03-08  本文已影响0人  代码的路

ElasticSearch是个开源分布式搜索引擎,提供搜集、分析、存储数据三大功能。它的特点有:分布式,零配置,自动发现,索引自动分片,索引副本机制,restful风格接口,多数据源,自动搜索负载等。主要负责将日志索引并存储起来,方便业务方检索查询。

1 安装ES

下载地址:https://www.elastic.co/cn/downloads/elasticsearch

选择Windows版本,我下载的是7.17.0。解压后即可完成安装。

进入bin文件, 双击执行 elasticsearch.bat,然后打开浏览器,进入页面: http://localhost:9200,看到以下输出,表示启动成功。

2 Spring项目

项目GitHub地址:https://github.com/Snowstorm0/learn-es

项目Gitee地址:https://gitee.com/Snowstorm0/learn-es

2.1 配置ES客户端

public class RestClientConfig extends AbstractElasticsearchConfiguration {
    @Override
    @Bean
    public RestHighLevelClient elasticsearchClient() {
        final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                .connectedTo("localhost:9200")
                .build();
        return RestClients.create(clientConfiguration).rest();
    }
}

2.2 创建User类

public class UserEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    private String name;
    private String job;
    private Double deposit;
    private Date processTime = new Date();
}

配置完成后,ElasticSearch即可像常规的数据库那样进行增删改查的操作。

2.3 配置数据库

spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/sys?characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC

3 运行项目

3.1 添加

调用添加接口:http://localhost:8080/user/add

添加User类的请求体:

{
  "id":"1",
  "name":"代码的路",
  "job":"码农",
  "deposit":100.0
}

可以看到添加成功:

3.2 读取

运行读取接口:http://localhost:8080/user/search/whole?key=码农

可以获得刚写入的User类,是完整结构:

运行读取接口:http://localhost:8080/user/search/es?key=码农

可以获得刚写入的User类,只有User结构:

打开数据库,无需手动创建表结构,即可看到User类也已经写入到数据库中:

因此可以刻直接从数据库读取。

 
 

学习更多编程知识,请关注我的公众号:

代码的路

上一篇 下一篇

猜你喜欢

热点阅读