【极光系列】springBoot集成elasticsearch

news/2024/7/7 5:53:37 标签: spring boot, elasticsearch, 后端, java

elasticsearch_0">【极光系列】springBoot集成elasticsearch

一.gitee地址

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

模块:aurora_elasticsearch

elasticsearch_8">二.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启动

elasticsearch_28">三.springBoot集成elasticsearch步骤

1.引入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>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配置

#服务配置
server:
  #端口
  port: 7005

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

  #es配置
elasticsearch:
  host: localhost
  port: 9200
  scheme: http

3.包结构

在这里插入图片描述

4.创建主启动类

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.创建配置类

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.创建工具类

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.创建控制类

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
在这里插入图片描述


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

相关文章

主动轮廓——计算机视觉中的图像分割方法

​ 一、说明 简单来说&#xff0c;计算机视觉就是为计算机提供类似人类的视觉。作为人类&#xff0c;我们很容易识别任何物体。我们可以很容易地识别山丘、树木、土地、动物等&#xff0c;但计算机没有眼睛&#xff0c;也没有大脑&#xff0c;因此它很难识别任何图像。计算机只…

大语言模型无代码构建知识图谱概述

2023年3月15日&#xff0c;ChatGPT4.0的横空出世&#xff0c;将人们对大语言模型的关注推到了风口浪尖。由于其在智能问答、翻译以及文本生成等工作任务上的卓越表现&#xff0c;业界一度出现了不再需要发展知识图谱相关技术的观点&#xff0c;知识图谱相关概念严重受挫。无可置…

Flutter中的AppLifecycleListener:应用生命周期监听器介绍及使用

引言 当你在Flutter中需要监听应用程序的生命周期变化时&#xff0c;可以使用AppLifecycleListener。在Flutter 3.13中&#xff0c;AppLifecycleListener被添加到Framework中&#xff0c;用于监听应用程序的生命周期变化&#xff0c;并响应退出应用程序的请求等支持。 在Flut…

多维时序 | Matlab实现CNN-BiLSTM-Mutilhead-Attention卷积双向长短期记忆神经网络融合多头注意力机制多变量时间序列预测

多维时序 | Matlab实现CNN-BiLSTM-Mutilhead-Attention卷积双向长短期记忆神经网络融合多头注意力机制多变量时间序列预测 目录 多维时序 | Matlab实现CNN-BiLSTM-Mutilhead-Attention卷积双向长短期记忆神经网络融合多头注意力机制多变量时间序列预测效果一览基本介绍程序设计…

教您如何下载保存钉钉视频到电脑本地

教您如何下载保存钉钉视频到电脑和手机相册地瓜网络技术 大家好&#xff0c;我们这边是地瓜网络技术&#xff01;30秒教会你下载钉钉视频&#xff01;现在很多群管理员把视频设置为禁止下载&#xff0c;导致我们无法正常的下载群直播回放视频&#xff0c; 今天我们就教大家如何…

【JupyterLab】在 conda 虚拟环境中 JupyterLab 的安装与使用

【JupyterLab】在 conda 虚拟环境中 JupyterLab 的安装与使用 1 JupyterLab 介绍2 安装2.1 Jupyter Kernel 与 conda 虚拟环境 3 使用3.1 安装中文语言包(Optional)3.2 启动3.3 常用快捷键3.3.1 命令模式下 3.4 远程访问个人计算机3.4.1 局域网下 1 JupyterLab 介绍 官方文档: …

PDF转PowerPoint - Java实现方法

通过编程实现PDF转PPT的功能&#xff0c;可以自动化转换过程&#xff0c;减少手动操作的工作量&#xff0c;并根据需要进行批量转换。将PDF文件转换为PPT文档后&#xff0c;可以利用PPT的丰富功能和动画效果&#xff0c;达到更好的演示效果。 在Java中&#xff0c;我们可以使用…

【linux】docker下nextcloud数据迁移

首先进行数据备份&#xff0c;找到nextclou的 /www/html/data/admin/files 对admin用户下的文件进行备份。然后在新电脑下执行以下操作&#xff1a; 1、切换root sudo su - 2、切换apt下载源 vi /etc/apt/sources.list 清华源 # 默认注释了源码镜像以提高 apt update 速度&…