【极光系列】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: localhostport: 9200scheme: 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;@Beanpublic 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 {@Autowiredprivate 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);@Autowiredprivate 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