【极光系列】springBoot集成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依赖

<?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.mfbz.cn/a/336776.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

高速CAN总线 A C节点竞争总线时 电压分析(共ABC三个节点)

CAN 收发器放大图 ABC三节点框图如下图&#xff1a; 图① 简化过程同<<高速CAN总线 A节点发送 B节点接收 电压分析>> A C节点同时发送显性电平 如下图: 图② A C 节点同时发送显性电平, 则 4 个三极管全部导通, 假定三极管压降0.5V 则电路简化如下图.(导通分析参…

【Qml-数据模型和视图】

Qml编程指南 VX&#xff1a;hao541022348 ■ 数据模型和视图■ ■ 数据模型和视图 QML使用了与Qt中Model-View类似的结构模型类提供了数据模型可以使QML的简单数据&#xff0c;或者复杂的C数据 QML: ListModel, XmlListModel, VisualItemModelC: QAbstractItemModel, QStringL…

记一次多平台免杀PHP木马的制作过程

注意&#xff1a;本文转载自本作者稀土掘金博客 博客地址&#xff1a; 御坂19008号 的个人主页 - 动态 - 掘金 文章目录 前言声明绕过情况使用方法运行环境绕过点介绍技术原理讲解变量传值覆盖模块代码执行阻断模块InazumaPuzzle程序锁定器PerlinNoise危险函数生成与执行类构造…

chapter1-爬虫那些事

背景 这个事情还要从Google或者百度说起。目前的搜索引擎&#xff0c;一般都拥有自己的一套网页检索算法&#xff0c;方便大家迅速的找到需要的网页。但是&#xff0c;当我们在使用各种搜索引擎的时候&#xff0c;是否思考过这样一个问题&#xff1a;搜索引擎是如何搜索到最新…

Linux问题 apt-get install时 无法解析域名“cn.archive.ubuntu.com”

问题描述: 在安装程序时会出现无法解析域名的错误 解决办法: 1、编辑文件 sudo vim /etc/resolv.conf 2、在最后加上(按键 i 进入编辑模式) nameserver 8.8.8.8 3、保存退出(:wq)

【Vue】使用 Vuex 作为状态管理

【Vue】使用 Vuex 作为状态管理 Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式和库。它使用单一状态树&#xff0c;这意味着这个对象包含了全部的应用层级状态&#xff0c;并且以一种相对集中的方式存在。这也意味着&#xff0c;通常单个项目中只有一个 Vuex store。Vue…

IDEA在重启springboot项目时没有自动重新build

IDEA在重启springboot项目时没有自动重新build 问题描述 当项目里面某些依赖或者插件更新了&#xff0c;target的class文件没有找到&#xff0c;导致不是我们需要的效果。 只能手动的清理target文件&#xff0c;麻烦得很 &#xff0c; 单体项目还好说&#xff0c;一次清理就…

Transformer|1.4 CNN遇到的问题与窘境

文章目录 CNN遇到的问题与窘境transformer 的优势 CNN遇到的问题与窘境 判断一个人是否为美人&#xff0c;既要看她各个五官&#xff0c;也要看她各个五官占的比例和协调。 既要照顾好局部信息&#xff0c;也要照顾好全局信息。 局部信息用小的感受野进行感受&#xff0c;而全局…

KKVIEW远程控制软件介绍

KKVIEW是一款全功能远程控制软件&#xff0c;可以随时随地访问家里或公司设备。KKVIEW,连接自由&#xff0c;KKVIEW旨在帮助用户在远程技术支持、远程办公、远程教育等领域便利的开展工作。 [主要功能] 远程桌面 一键远程显示远程桌面&#xff0c;一键开启远程控制&#xff0…

单元测试体系集成

JUnit 是一个基于 Java 语言的单元测试框架&#xff0c;可以用它来编写单元测试用例&#xff0c;用途广泛能被各种工具支持&#xff0c;每个 JUnit 单元测试相对独立&#xff0c;运行方便&#xff0c;结果的展示清晰&#xff1b;也可以把它与持续集成工具 Jenkins 进行集成&…

《WebKit 技术内幕》之五(4): HTML解释器和DOM 模型

4 影子&#xff08;Shadow&#xff09;DOM 影子 DOM 是一个新东西&#xff0c;主要解决了一个文档中可能需要大量交互的多个 DOM 树建立和维护各自的功能边界的问题。 4.1 什么是影子 DOM 当开发这样一个用户界面的控件——这个控件可能由一些 HTML 的标签元素…

Rust - 初识结构体

struct&#xff0c;或者 structure&#xff0c;是一个自定义数据类型&#xff0c;允许命名和包装多个相关的值&#xff0c;从而形成一个有意义的组合。如果你熟悉一门面向对象语言&#xff0c;struct 就像对象中的数据属性。 定义并实例化结构体 结构体和之前介绍过的元组类似…

5 python快速上手

数据类型&#xff08;上&#xff09; 1.整型1.1 定义1.2 独有功能1.3 公共功能1.4 转换1.5 其他1.5.1 长整型1.5.2 地板除 2. 布尔类型2.1 定义2.2 独有功能2.3 公共功能2.4 转换2.5 其他2.5.1 做条件自动转换 3.字符串类型3.1 定义3.2 独有功能&#xff08;18/48&#xff09;练…

Minio文件分片上传实现

资源准备 MacM1Pro 安装Parallels19.1.0请参考 https://blog.csdn.net/qq_41594280/article/details/135420241 MacM1Pro Parallels安装CentOS7.9请参考 https://blog.csdn.net/qq_41594280/article/details/135420461 部署Minio和整合SpringBoot请参考 https://blog.csdn.net/…

stm32 FOC系列 直流有刷控制原理

1、直流有刷驱动板 使用三极管搭建的简易 H 桥电路&#xff0c;如图 5.3.1 所示&#xff1a; 图 5.3.1 是使用三极管搭建的简易 H 桥电路&#xff0c;其中 MOTOR 表示直流有刷电机&#xff0c; Q1、 Q2、 Q3 和 Q4 为 4 个三极管&#xff0c;其中 Q1 和 Q3 接在了电源正极&…

Windows如何部署TortoiseSVN客户端

文章目录 前言1. TortoiseSVN 客户端下载安装2. 创建检出文件夹3. 创建与提交文件4. 公网访问测试 前言 TortoiseSVN是一个开源的版本控制系统&#xff0c;它与Apache Subversion&#xff08;SVN&#xff09;集成在一起&#xff0c;提供了一个用户友好的界面&#xff0c;方便用…

GitHub图床TyporaPicGo相关配置

本文作者&#xff1a; slience_me 文章目录 GitHub图床&Typora&PicGo相关配置1. Github配置2. picGo配置3. Typora配置 GitHub图床&Typora&PicGo相关配置 关于Typora旧版的百度网盘下载路径 链接&#xff1a;https://pan.baidu.com/s/12mq-dMqWnRRoreGo4MTbKg?…

DolphinDB学习(1):数据库的增删查与常用操作

下载并配置好DolphinDB&#xff0c;同时添加vscode的插件&#xff0c;我们就在vscode上进行操作 创建xxx.dos文件后&#xff0c;就会被识别为DolphinDB的运行文件&#xff0c;非常方便 文章目录 登录数据库的操作创建数据库查找与删除数据库 示例 登录 如果是vscode&#xff…

微信公众号服务器配置启用, Java示例

微信公众号接入指南文档https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Access_Overview.html 在微信公众号的服务器配置中&#xff0c;首先需要编写Java代码来处理微信服务器的验证请求。以下是Java示例代码&#xff0c;然后我将为你提供启用服务器配置…

鸿蒙harmony--数据库sqlite详解

今天是1月20号星期六&#xff0c;早安&#xff0c;岁末大寒至&#xff0c;静后春归来。愿他乡故人&#xff0c;漂泊有归宿&#xff0c;前程有奔赴&#xff0c;愿人间不寒&#xff0c;温暖常伴&#xff0c;诸事顺利&#xff0c;喜乐长安。 目录 一&#xff0c;定义 二&#xff…
最新文章