【极光系列】springBoot集成elasticsearch

news2024/9/21 22:26:37

【极光系列】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.coloradmin.cn/o/1398472.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

掌握大模型这些优化技术,优雅地进行大模型的训练和推理!

ChatGPT于2022年12月初发布&#xff0c;震惊轰动了全世界&#xff0c;发布后的这段时间里&#xff0c;一系列国内外的大模型训练开源项目接踵而至&#xff0c;例如Alpaca、BOOLM、LLaMA、ChatGLM、DeepSpeedChat、ColossalChat等。不论是学术界还是工业界&#xff0c;都有训练大…

5分钟教会你如何在生产环境debug代码

前言 有时出现的线上bug在测试环境死活都不能复现&#xff0c;靠review代码猜测bug出现的原因&#xff0c;然后盲改代码直接在线上测试明显不靠谱。这时我们就需要在生产环境中debug代码&#xff0c;快速找到bug的原因&#xff0c;然后将锅丢出去。 生产环境的代码一般都是关闭…

Peter算法小课堂—拓扑排序与最小生成树

拓扑排序 讲拓扑排序前&#xff0c;我们要先了解什么是DAG树。所谓DAG树&#xff0c;就是指“有向无环图”。请判断下列图是否是DAG图 第一幅图&#xff0c;它不是DAG图&#xff0c;因为它形成了一个环。第二幅图&#xff0c;它也不是DAG图&#xff0c;因为它没有方向。第三幅…

Red Hat Enterprise Linux 6.10 安装图解

引导和开始安装 选择倒计时结束前&#xff0c;通过键盘上下键选择下图框选项&#xff0c;启动图形化安装过程。需要注意的不同主板默认或者自行配置的固件类型不一致&#xff0c;引导界面有所不同。也就是说使用UEFI和BIOS的安装引导界面是不同的&#xff0c;如图所示。若手动调…

SpringBoot 服务注册IP选择问题

问题 有时候我们明明A\B服务都注册成功了&#xff0c;但是相互之间就是访问不了&#xff0c;这大概率是因为注册时选择IP时网卡选错了&#xff0c;当我们本地电脑有多个网卡时&#xff0c;程序会随机选择一个有IPV4的网卡&#xff0c;然后读取IPv4的地址 比如我的电脑有3个网…

mysql中的联合索引为什么要遵循最佳左前缀法则?

mysql中的联合索引为什么要遵循最佳左前缀法则&#xff1f; 一、什么是联合索引二、联合索引的优化1.常规的写法&#xff08;回表查询&#xff09;2.优化写法&#xff08;索引覆盖&#xff09; 三、 为什么要遵循最佳左前缀法则&#xff1f;1.如下查询语句可以使用到索引&#…

[C#]C# winform部署yolov8目标检测的openvino模型

【官方框架地址】 https://github.com/ultralytics/ultralytics 【openvino介绍】 OpenVINO&#xff08;Open Visual Inference & Neural Network Optimization&#xff09;是由Intel推出的&#xff0c;用于加速深度学习模型推理的工具套件。它旨在提高计算机视觉和深度学…

【LeetCode】数学精选4题

目录 1. 二进制求和&#xff08;简单&#xff09; 2. 两数相加&#xff08;中等&#xff09; 3. 两数相除&#xff08;中等&#xff09; 4. 字符串相乘&#xff08;中等&#xff09; 1. 二进制求和&#xff08;简单&#xff09; 从字符串的右端出发向左做加法&#xff0c;…

Unity3D学习之UI系统——GUI

文章目录 1. 前言2. 工作原理和主要作用3. 基础控件3.1 重要参数及文本和按钮3.1.1 GUI 共同点3.1.2 文本控件3.1.3 按钮控件 3.2 多选框和单选框3.2.1 多选框3.2.2 单选框3.2.3 输入框3.2.4 拖动条 3.3 图片绘制和框3.3.1 图片3.3.2 框绘制 4 工具栏和选择网格4.1 工具栏4.2 选…

数据分析中常用的指标或方法

一、方差与标准差二、协方差三、皮尔逊系数四、斯皮尔曼系数五、卡方检验六、四分位法和箱线图七、 一、方差与标准差 总体方差 V a r ( x ) σ 2 ∑ i 1 n ( x i − x ˉ ) 2 n ∑ i 1 n x i 2 − n x ˉ 2 n E ( x 2 ) − [ E ( x ) ] 2 Var(x)\sigma^2\frac {\sum\l…

RK3566 linux加入uvc app

一、集成应用 SDK中external/uvc_app/目录提供了将板卡模拟成uvc camera的功能。如果external目录下没有uvc_app和minilogger&#xff0c;可从其它sdk中拷贝。需要拷贝以下文件&#xff1a; external\uvc_app external\minilogger \buildroot\package\rockchip\uvc_app \buil…

MCM备赛笔记——图论模型

Key Concept 图论是数学的一个分支&#xff0c;专注于研究图的性质和图之间的关系。在图论中&#xff0c;图是由顶点&#xff08;或节点&#xff09;以及连接这些顶点的边&#xff08;或弧&#xff09;组成的。图论的模型广泛应用于计算机科学、通信网络、社会网络、生物信息学…

2024年阿里云优惠券和代金券领取,活动整理服务器价格表

2024阿里云优惠活动&#xff0c;免费领取阿里云优惠代金券&#xff0c;阿里云优惠活动大全和云服务器优惠价格表&#xff0c;阿里云ECS服务器优惠价99元一年起&#xff0c;轻量服务器优惠价61元一年&#xff0c;阿里云服务器网aliyunfuwuqi.com分享阿里云优惠券免费领取、优惠活…

【已解决】namespace “Ui“没有成员 xxx

先说笔者遇到的问题&#xff0c;我创建一个QWidget ui文件&#xff0c;然后编辑的七七八八后&#xff0c;想要用.h与.cpp调用其&#xff0c;编译通过&#xff0c;结果报了这个错误&#xff0c;本方法不是普适性&#xff0c;但是确实解决了这个鸟问题。 问题来源 搭建ui后&…

MT36291替代MT3608 FP6291 低成本 用于移动电源,蓝牙音箱,便携式设备等

航天民芯原装MT36291 SOT23-6 PIN对PIN替代FP6291LR-G1 MT3608等&#xff0c;低成本&#xff0c;用于移动电源&#xff0c;蓝牙音箱&#xff0c;便携式设备等领域。 TEL:18028786817 专注于电源管理IC 一级代理 技术支持 欢迎试样&#xff01; 描述 MT36291是一个恒定频…

位运算的奇技淫巧

常见位运算总结&#xff1a; 1、基础位运算 左移<<运算 将二进制数向左移位操作&#xff0c;高位溢出则丢弃&#xff0c;低位补0。 右移>>运算 右移位运算中&#xff0c;无符号数和有符号数的运算并不相同。对于无符号数&#xff0c;右移之后高位补0&#xff…

软件测试|Python字典的访问方式你了解吗?

简介 Python中的字典&#xff08;dictionary&#xff09;是一种非常有用的数据结构&#xff0c;它允许您存储键-值对&#xff0c;从而可以快速查找、插入和删除数据。本文将详细介绍如何访问字典中的数据&#xff0c;包括基本访问、循环遍历、使用内置方法以及处理不存在的键等…

Redis持久化和集群架构

目录 Redis持久化 RDB快照&#xff08;snapshot&#xff09; RDB优点 RDB缺点 RDB的触发机制 AOF持久化 AOF文件重写 AOF触发机制 混合模式 Redis主从架构 Redis哨兵高可用架构 Redis Cluster架构 槽位定位算法 跳转重定位 Redis集群节点间的通信机制 Redis持久化…

centos安装主从mysql集群

在 CentOS 系统上安装和配置 MySQL 主从复制环境的步骤与 Debian/Ubuntu 系统有所不同。以下是在 CentOS 系统上进行配置的详细步骤&#xff1a; 步骤 1&#xff1a;在主服务器上安装和配置 MySQL&#xff08;10.206.0.13&#xff09; 安装 MySQL 服务器: 首先&#xff0c;添加…

NeRF资料整理

文章目录 1.NeRF原理讲解2.NeRF中用到的NDC空间坐标系3.NeRF中的sample_pdf概率采样函数 1.NeRF原理讲解 nerf 原理讲解&#xff1a;这个视频对NeRF中体渲染公式的讲解和推导非常好&#xff0c;言简意赅&#xff0c;而且和论文、代码都可以对应上。 2.NeRF中用到的NDC空间坐标…