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:

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;

    @Bean
    public 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 {

	@Autowired
	private RestHighLevelClient restHighLevelClient;


	@org.junit.Test
	public void test() throws IOException {
		CreateIndexRequest request = new CreateIndexRequest("message");
		CreateIndexResponse response = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
		System.out.println(response.isAcknowledged());
	}


	@org.junit.Test
	public 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.Test
	public void testDeleteMessageIndex() throws IOException {
		// 1.创建Request对象
		DeleteIndexRequest request = new DeleteIndexRequest("r_rideinfo");
		// 2.发送请求
		restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
	}


}

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

相关推荐
码蜂窝编程官方1 分钟前
【含开题报告+文档+PPT+源码】基于SpringBoot+Vue的虎鲸旅游攻略网的设计与实现
java·vue.js·spring boot·后端·spring·旅游
hummhumm19 分钟前
第 25 章 - Golang 项目结构
java·开发语言·前端·后端·python·elasticsearch·golang
许苑向上1 小时前
Dubbo集成SpringBoot实现远程服务调用
spring boot·后端·dubbo
郑祎亦2 小时前
Spring Boot 项目 myblog 整理
spring boot·后端·java-ee·maven·mybatis
计算机毕设指导63 小时前
基于 SpringBoot 的作业管理系统【附源码】
java·vue.js·spring boot·后端·mysql·spring·intellij-idea
paopaokaka_luck3 小时前
[371]基于springboot的高校实习管理系统
java·spring boot·后端
java1234_小锋4 小时前
Elasticsearch中的节点(比如共20个),其中的10个选了一个master,另外10个选了另一个master,怎么办?
大数据·elasticsearch·jenkins
Elastic 中国社区官方博客4 小时前
Elasticsearch 开放推理 API 增加了对 IBM watsonx.ai Slate 嵌入模型的支持
大数据·数据库·人工智能·elasticsearch·搜索引擎·ai·全文检索
我的运维人生4 小时前
Elasticsearch实战应用:构建高效搜索与分析平台
大数据·elasticsearch·jenkins·运维开发·技术共享
捂月4 小时前
Spring Boot 深度解析:快速构建高效、现代化的 Web 应用程序
前端·spring boot·后端