【极光系列】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下载

【极光系列】springBoot集成elasticsearch_第1张图片

【极光系列】springBoot集成elasticsearch_第2张图片

【极光系列】springBoot集成elasticsearch_第3张图片

2.解压缩,启动服务

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

三.springBoot集成elasticsearch步骤

1.引入pom.xml依赖



    4.0.0

    com.xsy
    aurora_elasticsearch
    1.0-SNAPSHOT

    
    
        org.springframework.boot
        spring-boot-starter-parent
        2.3.5.RELEASE
    

    
    
        
        1.8
        
        3.8.1
        
        UTF-8
        
        UTF-8
        
        1.2.75
        
        2.3.0
        
        7.6.2
    

    
    

        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
        
            org.projectlombok
            lombok
        

        
        
            com.alibaba
            fastjson
            ${fastjson.version}
        

        
        
            org.elasticsearch.client
            elasticsearch-rest-high-level-client
            ${elasticsearch.version}
        

        
    

    
    
        ${project.name}
        
        
            
                src/main/resources
            
            
                src/main/java
                
                    **/*.xml
                
            
        

        
        
            
                
                
                    org.springframework.boot
                    spring-boot-maven-plugin
                    ${spring.boot.version}
                    
                        true
                        ${project.build.finalName}
                    
                    
                        
                            
                                repackage
                            
                        
                    
                

                
                
                    maven-compiler-plugin
                    ${maven.plugin.version}
                    
                        ${java.version}
                        ${java.version}
                        UTF-8
                        
                            -parameters
                        
                    
                
            
        
    

    
    
        
            aliyun-repos
            https://maven.aliyun.com/nexus/content/groups/public/
            
                false
            
        
    

    
    
        
            aliyun-plugin
            https://maven.aliyun.com/nexus/content/groups/public/
            
                false
            
        
    


2.修改application配置

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

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

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

3.包结构

【极光系列】springBoot集成elasticsearch_第4张图片

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
【极光系列】springBoot集成elasticsearch_第5张图片

你可能感兴趣的:(极光系列,spring,boot,elasticsearch,后端,java)