前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【极光系列】springBoot集成elasticsearch

【极光系列】springBoot集成elasticsearch

作者头像
夏之以寒
发布2024-03-04 17:28:37
1370
发布2024-03-04 17:28:37
举报
文章被收录于专栏:Elasticsearch专栏

【极光系列】springBoot集成elasticsearch

一.gitee地址

直接下载解压可用 https://gitee.com/shawsongyue/aurora.git

模块:aurora_elasticsearch

二.windows安装elasticsearch

tips:注意es客户端版本要与java依赖版本一致,目前使用7.6.2版本

elasticsearch 7.6.2版本客户端下载: https://www.elastic.co/cn/downloads/elasticsearch

1.下载对应版本资源包

登录页面–》View path releases–》选择7.6.2版本–》window下载

2.解压缩,启动服务

直接点击E:\elasticsearch-7.6.2\bin\elasticsearch.bat启动

三.springBoot集成elasticsearch步骤

1.引入pom.xml依赖
代码语言:javascript
复制
<?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.xsy</groupId>
    <artifactId>aurora_elasticsearch</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!--基础SpringBoot依赖-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.5.RELEASE</version>
    </parent>

    <!--属性设置-->
    <properties>
        <!--java_JDK版本-->
        <java.version>1.8</java.version>
        <!--maven打包插件-->
        <maven.plugin.version>3.8.1</maven.plugin.version>
        <!--编译编码UTF-8-->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <!--输出报告编码UTF-8-->
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <!--json数据格式处理工具-->
        <fastjson.version>1.2.75</fastjson.version>
        <!--json数据格式处理工具-->
        <xxljob.version>2.3.0</xxljob.version>
        <!--elasticsearch依赖-->
        <elasticsearch.version>7.6.2</elasticsearch.version>
    </properties>

    <!--通用依赖-->
    <dependencies>

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

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

        <!-- Lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <!-- json -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>${fastjson.version}</version>
        </dependency>

        <!--es    start-->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>

        <!--es  end-->
    </dependencies>

    <!--编译打包-->
    <build>
        <finalName>${project.name}</finalName>
        <!--资源文件打包-->
        <resources>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>

        <!--插件统一管理-->
        <pluginManagement>
            <plugins>
                <!--maven打包插件-->
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                    <version>${spring.boot.version}</version>
                    <configuration>
                        <fork>true</fork>
                        <finalName>${project.build.finalName}</finalName>
                    </configuration>
                    <executions>
                        <execution>
                            <goals>
                                <goal>repackage</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>

                <!--编译打包插件-->
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>${maven.plugin.version}</version>
                    <configuration>
                        <source>${java.version}</source>
                        <target>${java.version}</target>
                        <encoding>UTF-8</encoding>
                        <compilerArgs>
                            <arg>-parameters</arg>
                        </compilerArgs>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>

    <!--配置Maven项目中需要使用的远程仓库-->
    <repositories>
        <repository>
            <id>aliyun-repos</id>
            <url>https://maven.aliyun.com/nexus/content/groups/public/</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <!--用来配置maven插件的远程仓库-->
    <pluginRepositories>
        <pluginRepository>
            <id>aliyun-plugin</id>
            <url>https://maven.aliyun.com/nexus/content/groups/public/</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

</project>
2.修改application配置
代码语言:javascript
复制
#服务配置
server:
  #端口
  port: 7005

#spring配置
spring:
  #应用配置
  application:
    #应用名
    name: aurora_elasticsearch

  #es配置
elasticsearch:
  host: localhost
  port: 9200
  scheme: http
3.包结构
4.创建主启动类
代码语言:javascript
复制
package com.aurora;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author 浅夏的猫
 * @description 主启动类
 * @date 22:46 2024/1/13
 */
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
5.创建配置类
代码语言:javascript
复制
package com.aurora.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @description es配置
 * @author 浅夏的猫
 * @datetime 6:14 2024/1/20
*/
@Configuration
public class ElasticsearchConfig {

    @Value("${elasticsearch.host}")
    private String host;

    @Value("${elasticsearch.port}")
    private int port;

    @Value("${elasticsearch.scheme}")
    private String scheme;

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        return new RestHighLevelClient(
                RestClient.builder(new HttpHost(host, port, scheme)));
    }
}
6.创建工具类
代码语言:javascript
复制
package com.aurora.utils;

import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.rest.RestStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class ElasticsearchUtil {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    public boolean createIndex(String index) {
        boolean ackFlag = false;
        CreateIndexRequest request = new CreateIndexRequest(index);
        try {
            CreateIndexResponse response = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
            ackFlag = response.isAcknowledged();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ackFlag;
    }

    public boolean indexDocument(String index, String id, String jsonSource) {
        boolean ackFlag = false;
        IndexRequest request = new IndexRequest(index)
                .id(id)
                .source(jsonSource, XContentType.JSON);

        try {
            IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
            ackFlag = response.status() == RestStatus.CREATED || response.status() == RestStatus.OK;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ackFlag;
    }

    public String getDocument(String index, String id) {
        GetRequest getRequest = new GetRequest(index, id);
        String sourceAsString = null;
        try {
            sourceAsString = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT).getSourceAsString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sourceAsString;
    }

    public boolean updateDocument(String index, String id, String jsonSource) {
        boolean ackFLag = false;
        UpdateRequest request = new UpdateRequest(index, id)
                .doc(jsonSource, XContentType.JSON);

        try {
            UpdateResponse response = restHighLevelClient.update(request, RequestOptions.DEFAULT);
            ackFLag = response.status() == RestStatus.CREATED || response.status() == RestStatus.OK;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ackFLag;
    }

    public boolean deleteDocument(String index, String id) {
        boolean ackFlag = false;
        DeleteRequest request = new DeleteRequest(index, id);
        try {
            DeleteResponse response = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
            ackFlag = response.status() == RestStatus.OK;

        } catch (IOException e) {
            e.printStackTrace();
        }

        return ackFlag;
    }
}
7.创建控制类
代码语言:javascript
复制
package com.aurora.controller;

import com.alibaba.fastjson.JSONObject;
import com.aurora.utils.ElasticsearchUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @description 资源控制类
 * @author 浅夏的猫
 * @datetime 6:21 2024/1/20
*/
@RestController
@RequestMapping("resource")
public class ElasticsearhController {

    private static Logger logger = LoggerFactory.getLogger(ElasticsearhController.class);

    @Autowired
    private ElasticsearchUtil elasticsearchUtil;

    @RequestMapping("esOperate")
    public String esOperate(){
        String index="aurora-20240120";
        JSONObject esJsonObj = new JSONObject();
        String id="aurora002";
        esJsonObj.put("id",id);
        esJsonObj.put("resourceName","aurora源码下载包");
        esJsonObj.put("resourceUrl","http://baidu.com");
        esJsonObj.put("resourceType","1");
        esJsonObj.put("resourceDescribe","aurora资源下载包,大概10M");

        //插入
        boolean insertFlag = elasticsearchUtil.indexDocument(index, id, esJsonObj.toString());
        logger.info("插入数据是否成功:{}",insertFlag);
        //查询
        String document = elasticsearchUtil.getDocument(index,id);
        logger.info("从es索引查询数据:{}",document);
        //更新
        boolean updateFlag = elasticsearchUtil.updateDocument(index, id, esJsonObj.toString());
        logger.info("更新数据是否成功:{}",updateFlag);
        //删除
        boolean deleteFlag = elasticsearchUtil.deleteDocument(index, id);
        logger.info("删除数据是否成功:{}",deleteFlag);
        //查询
        String documentDelete = elasticsearchUtil.getDocument(index,id);
        logger.info("删除后,查询es索引查询数据:{}",documentDelete);

        return "ok";
    }

}
8.访问地址验证

http://localhost:7005/resource/esOperate

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-03-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 【极光系列】springBoot集成elasticsearch
    • 一.gitee地址
      • 二.windows安装elasticsearch
        • 1.下载对应版本资源包
        • 2.解压缩,启动服务
      • 三.springBoot集成elasticsearch步骤
        • 1.引入pom.xml依赖
        • 2.修改application配置
        • 3.包结构
        • 4.创建主启动类
        • 5.创建配置类
        • 6.创建工具类
        • 7.创建控制类
        • 8.访问地址验证
    相关产品与服务
    Elasticsearch Service
    腾讯云 Elasticsearch Service(ES)是云端全托管海量数据检索分析服务,拥有高性能自研内核,集成X-Pack。ES 支持通过自治索引、存算分离、集群巡检等特性轻松管理集群,也支持免运维、自动弹性、按需使用的 Serverless 模式。使用 ES 您可以高效构建信息检索、日志分析、运维监控等服务,它独特的向量检索还可助您构建基于语义、图像的AI深度应用。
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档