当前位置:主页 > java教程 > ElasticSearch整合SpringBoot

ElasticSearch整合SpringBoot搭建配置

发布:2023-03-27 10:30:02 59


本站精选了一篇相关的编程文章,网友厍泽惠根据主题投稿了本篇教程内容,涉及到ElasticSearch整合SpringBoot、ElasticSearch、SpringBoot、ElasticSearch整合SpringBoot相关内容,已被816网友关注,相关难点技巧可以阅读下方的电子资料。

ElasticSearch整合SpringBoot

前言

目前正在出一个Es专题系列教程, 篇幅会较多, 请持续关注码农之家

本节来给大家讲一下在Springboot中如何整合es~

本文偏实战一些,为了方便演示,本节示例沿用上节索引,好了, 废话不多说直接开整吧~

项目搭建

老规矩,先建maven项目,下面是我的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>
    <groupId>org.example</groupId>
    <artifactId>springboot-es-all</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
    </parent>
    <dependencies>
        <!--test-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <!--ElasticSearch 客户端依赖-->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-client</artifactId>
            <version>7.8.0</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.8.0</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.8.0</version>
        </dependency>
        <!--Hutool依赖-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.4</version>
        </dependency>
        <!--fast-json-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.58</version>
        </dependency>
        <dependency>
            <groupId> org.slf4j </groupId>
            <artifactId> slf4j-api </artifactId>
            <version> 1.6.4 </version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.25</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.1.3.RELEASE</version>
            </plugin>
        </plugins>
    </build>
</project>

这里我使用的是elasticsearch-rest-high-level-client官方客户端,建议大家尽量用官方的,因为随着es的不断升级,很多api都过时了,如果你使用spring-boot-starter-data-elasticsearch这个要依赖社区去维护,很多新特性你没法使用到,也会存在安全性问题。

配置客户端

启动类:

@SpringBootApplication
public class EsStudyApplication {
    public static void main(String[] args) {
        SpringApplication.run(EsStudyApplication.class, args);
    }
}

配置文件 application.yml:

server:
  port: 9000
elasticsearch:
  host: 0.0.0.0
  port: 9200
  username:
  password:

客户端配置 config.EsClientConfig:

@Configuration
public class EsClientConfig {
    @Value("${elasticsearch.host}")
    private String host;
    @Value("${elasticsearch.port}")
    private int port;
    @Value("${elasticsearch.username}")
    private String userName;
    @Value("${elasticsearch.password}")
    private String password;
    @Bean
    public RestHighLevelClient restHighLevelClient() {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost( host, port, "http")).setHttpClientConfigCallback(httpClientBuilder -&gt; {
                    httpClientBuilder.setMaxConnTotal(500);
                    httpClientBuilder.setMaxConnPerRoute(300);
                    return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                })
        );
        return restHighLevelClient;
    }
}

然后客户端我们就配好了,客户端的配置其实还有很多,感兴趣的同学自行查阅。后续使用的时候,直接导入RestHighLevelClient实例就好了

接着启动它,如果控制没有报错,说明配置没啥问题了, 记得要开启es服务~

索引API初探 & Index API

下面我们写一点测试用例,来验证我们是否可以操作es,为了方便演示,这里直接使用SpringBootTest来测试,大家平时在写springboot项目,类测试的时候也可以这么做

ping

新建api.IndexApi,调用ping()方法来测试是否链接成功:

@Slf4j
@SpringBootTest
public class IndexApi {
    /**
     * es 索引
     */
    public static final String index = "study";
    @Autowired
    private RestHighLevelClient client;
    @Test
    public void ping() throws IOException {
        if(client.ping(RequestOptions.DEFAULT)) {
            log.info("链接成功");
        }else {
            log.info("链接失败 !");
        }
    }
}    

点击IndexApi左上角的绿色箭头启动测试用例, 如果报错,尝试添加以下 注解

@RunWith(SpringRunner.class)
@SpringBootTest(classes = { EsStudyApplication.class })
public class IndexApi {....}

返回:

链接成功

说明客户端es服务端是通的

创建索引 & create

通过前面的学习,有了一定的基础之后,回到代码中其实就是调调方法,因为你知道了这个代码的逻辑做了什么操作。下面来看下如何创建索引:

/**
     * 创建索引
     */
    @Test
    public void createIndex() throws IOException {
        CreateIndexRequest request = new CreateIndexRequest(index);
        CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
        log.info("创建索引 ===> "+ JSONObject.toJSONString(createIndexResponse)); // 创建索引 ===> {"acknowledged":true,"fragment":false,"shardsAcknowledged":true}
    }

大家可以返回到kibana中查看索引是否被创建,从而验证代码执行是否成功

添加别名:

// alias
request.alias(new Alias("study_alias"));

索引设置settings:

// index settings
request.settings(
        Settings.builder()
                .put("index.number_of_shards", 3)
                .put("index.number_of_replicas", 2)
);

索引映射mapping:

 // index mappings
//        {
//            "mapping": {
//            "_doc": {
//                "properties": {
//                    "name": {
//                        "type": "text"
//                    }
//                }
//            }
//        }
//        }
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject();
{
    builder.startObject("properties");
    {
        builder.startObject("name");
        {
            builder.field("type", "text");
        }
        builder.endObject();
    }
    builder.endObject();
}
builder.endObject();
request.mapping(builder);

设置请求超时时间:

// 请求设置
request.setTimeout(TimeValue.timeValueMinutes(1));

索引是否存在 & exist

 /**
    * 判断索引是否存在
    * @throws IOException
    */
@Test
public void existIndex() throws IOException {
    GetIndexRequest request = new GetIndexRequest(index);
    boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
    log.info("索引{}存在 ===> {}", index, exists);
}

删除索引

 /**
    * 删除索引
    * @throws IOException
    */
@Test
public void delIndex() throws IOException {
    DeleteIndexRequest request = new DeleteIndexRequest(index);
    AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
    log.info("删除索引 ===> {}", JSONObject.toJSONString(delete)); // 删除索引 ===> {"acknowledged":true,"fragment":false}
}

结束语

下节带大家看下文档操作相关的api,也是我们业务中使用最多的api~

更多关于ElasticSearch整合SpringBoot的资料请关注码农之家其它相关文章!


参考资料

相关文章

  • springboot多环境配置文件及自定义配置文件路径详解

    发布:2023-04-08

    这篇文章主要介绍了springboot多环境配置文件及自定义配置文件路径,文中给大家介绍了classpath的基本概念讲解及自定义springboot配置文件路径的相关知识,需要的朋友可以参考下


  • SpringBoot配置的加载流程详细分析

    发布:2023-03-02

    了解内部原理是为了帮助我们做扩展,同时也是验证了一个人的学习能力,如果你想让自己的职业道路更上一层楼,这些底层的东西你是必须要会的,这篇文章主要介绍了SpringBoot配置的加载流程


  • SpringBoot controller参数校验方法详细讲解

    发布:2023-04-26

    这篇文章主要介绍了SpringBoot在Controller层接收参数的常用方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下


  • 记一次Maven项目改造成SpringBoot项目的过程实践

    记一次Maven项目改造成SpringBoot项目的过程实践

    发布:2022-10-17

    为网友们分享了关于Maven的教程,本文主要介绍了Maven项目改造成SpringBoot项目的过程实践,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下


  • 基于SpringBoot 使用 Flink 收发Kafka消息的示例详解

    发布:2023-03-01

    这篇文章主要介绍了基于SpringBoot 使用 Flink 收发Kafka消息,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下


  • SpringBoot2零基础到精通之自动配置底层分析及小技巧

    SpringBoot2零基础到精通之自动配置底层分析及小技巧

    发布:2022-10-21

    给网友们整理关于SpringBoot的教程,SpringBoot是一种整合Spring技术栈的方式(或者说是框架),同时也是简化Spring的一种快速开发的脚手架,本篇让我们一起学习自动配置的底层分析与一些开发中的小技巧


  • springboot 自定义启动器的实现

    发布:2023-04-17

    本文主要介绍了springboot 自定义启动器的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧


  • ElasticSearch不停机重建索引延伸思考及优化详解

    发布:2023-04-11

    这篇文章主要为大家介绍了ElasticSearch不停机重建索引延伸思考及优化详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪


网友讨论