当前位置: 首页 > news >正文

spring boot 集成es使用

pom添加依赖

我的es是7.17.3版本,spring boot是2.2.2.RELEASE版本,仅供参考:

<!-- Elasticsearch RestHighLevelClient -->
<dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId><version>7.17.3</version><exclusions><exclusion><artifactId>elasticsearch-rest-client</artifactId><groupId>org.elasticsearch.client</groupId></exclusion></exclusions>
</dependency>
<dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-client</artifactId><version>7.17.3</version>
</dependency>
<dependency><groupId>org.elasticsearch</groupId><artifactId>elasticsearch</artifactId><version>7.17.3</version>
</dependency>
本地构建es服务器:

想用连接es,需要有一个es服务器,我同样安装了kibana,用的是docker-compose的方式,docker-compose.yaml文件内容:

version: '3.7'
 
services: 
    elasticsearch:
        image: docker.elastic.co/elasticsearch/elasticsearch:7.17.3
        ports:
            - 9200:9200
        volumes:
            - ./es/esdata:/usr/share/elasticsearch/data
            - ./es/logs:/usr/share/elasticsearch/logs
            - ./es/plugins:/usr/share/elasticsearch/plugins
        environment:
            - discovery.type=single-node
            - xpack.security.enabled=false
            - ES_JAVA_OPTS=-Xms1g -Xmx10g
        deploy:
            replicas: 1
            restart_policy:
                condition: on-failure
            resources:
                limits:
                    cpus: '4'
                    memory: 2G
        networks:
            - _test

    kibana:
        image: kibana:7.17.3
        ports:
            - 5601:5601
        environment:
            - ELASTICSEARCH_HOSTS=http://elasticsearch:9200
        depends_on:
            - elasticsearch
        networks:
            - _test            
            

networks:
    _network:
        external: true
        driver: overlay
        name: test
 

项目代码配置es的配置文件

连接es的ip和端口

package com.susu.es;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;@Configuration
public class ElasticsearchConfig {@Value("${elasticsearch.host}")private String host;@Value("${elasticsearch.port}")private String port;@Beanpublic RestHighLevelClient restHighLevelClient() {return new RestHighLevelClient(RestClient.builder(HttpHost.create(host+":"+port)).setRequestConfigCallback(requestConfigBuilder -> {return requestConfigBuilder.setConnectTimeout(5000 * 1000) // 连接超时(默认为1秒).setSocketTimeout(6000 * 1000);// 套接字超时(默认为30秒)}));}}
编写测试类进行连接:
package com.susu.es;import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.*;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xcontent.XContentFactory;
import org.elasticsearch.xcontent.XContentType;
import org.json.JSONObject;
import org.junit.jupiter.api.Order;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;import java.io.IOException;
import java.util.ArrayList;
import java.util.List;import static cn.hutool.http.webservice.SoapUtil.createClient;
import static cn.hutool.json.XMLTokener.entity;@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class Test {@Autowiredprivate RestHighLevelClient restHighLevelClient;@org.junit.Testpublic void test() throws IOException {CreateIndexRequest request = new CreateIndexRequest("message");CreateIndexResponse response = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);System.out.println(response.isAcknowledged());}@org.junit.Testpublic void testExistsMessageIndex() throws IOException {// 1.创建Request对象GetIndexRequest request = new GetIndexRequest("message");// 2.发送请求boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);// 3.输出System.err.println(exists ? "索引库已经存在!" : "索引库不存在!");}@org.junit.Testpublic void testDeleteMessageIndex() throws IOException {// 1.创建Request对象DeleteIndexRequest request = new DeleteIndexRequest("r_rideinfo");// 2.发送请求restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);}}

已经连接成功,可以使用。

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • (十三)Flink SQL
  • 海南省政协主席李荣灿调研宇乐乐影业
  • 如何使用 Java 将 JSON 数据转换为 YAML 文件
  • python并发与并行(四) ———— 用queue来协调多个线程之间的工作进度
  • 【Qt】基于VTK9.1+VS2019+Qt5.15.2的点云可视化程序开发
  • 【C++ Primer Plus习题】6.9
  • Elasticsearch(面试篇)
  • 第三十九篇-TeslaP40+CosyVoice-安装
  • 云计算实训38——docker网络、跨主机容器之间的通讯
  • STM32(F103ZET6)第十九课:FreeRtos的移植和使用
  • SQLserver使用sql语句创建主键,外键,唯一约束,自增
  • CSS中的元素布局与定位详细说明
  • # 移动硬盘误操作制作为启动盘数据恢复问题
  • Android插件化技术之加载未安装APK
  • 数据链路层(Mac帧,报头字段,局域网通信原理),MTU,MSS,ip报文的分包与组装(ip报头字段介绍,组装过程,判断是否被分片/收到全部分片)
  • 《Javascript数据结构和算法》笔记-「字典和散列表」
  • C++类的相互关联
  • Consul Config 使用Git做版本控制的实现
  • create-react-app项目添加less配置
  • HTML-表单
  • JS正则表达式精简教程(JavaScript RegExp 对象)
  • LeetCode541. Reverse String II -- 按步长反转字符串
  • 从setTimeout-setInterval看JS线程
  • 多线程 start 和 run 方法到底有什么区别?
  • 普通函数和构造函数的区别
  • 如何正确配置 Ubuntu 14.04 服务器?
  • 听说你叫Java(二)–Servlet请求
  • 优秀架构师必须掌握的架构思维
  • media数据库操作,可以进行增删改查,实现回收站,隐私照片功能 SharedPreferences存储地址:
  • 专访Pony.ai 楼天城:自动驾驶已经走过了“从0到1”,“规模”是行业的分水岭| 自动驾驶这十年 ...
  • ​Benvista PhotoZoom Pro 9.0.4新功能介绍
  • ​TypeScript都不会用,也敢说会前端?
  • ​渐进式Web应用PWA的未来
  • ​如何在iOS手机上查看应用日志
  • #stm32整理(一)flash读写
  • $var=htmlencode(“‘);alert(‘2“); 的个人理解
  • (11)MSP430F5529 定时器B
  • (2024.6.23)最新版MAVEN的安装和配置教程(超详细)
  • (3)Dubbo启动时qos-server can not bind localhost22222错误解决
  • (苍穹外卖)day03菜品管理
  • (二)延时任务篇——通过redis的key监听,实现延迟任务实战
  • (附源码)springboot 个人网页的网站 毕业设计031623
  • (个人笔记质量不佳)SQL 左连接、右连接、内连接的区别
  • (六)软件测试分工
  • (十一)c52学习之旅-动态数码管
  • (四)进入MySQL 【事务】
  • ***linux下安装xampp,XAMPP目录结构(阿里云安装xampp)
  • .gitignore文件使用
  • .net core 6 使用注解自动注入实例,无需构造注入 autowrite4net
  • .net core 依赖注入的基本用发
  • .net framework 4.0中如何 输出 form 的name属性。
  • .net oracle 连接超时_Mysql连接数据库异常汇总【必收藏】
  • .net refrector
  • .NET 服务 ServiceController
  • .NET 事件模型教程(二)