SpringBoot + ES basic project construction example

[Search series] ES basic project construction

I haven’t written ES-related blog posts before, and now I’m starting to make up lessons. It is expected that 5-6 blog posts will show the use of es to your friends; this article will be the first blog post of es combined with springboot, and the basic project environment will be built.

<!-- more -->

I. Project Construction

1. Project dependencies

This project is developed with the help of SpringBoot 2.2.1.RELEASE + maven 3.5.3 + IDEA

Open a web service for testing

<dependencies>
    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-high-level-client</artifactId>
    </dependency>
</dependencies>

2. Configuration Information

Configuration file application.yml, pay attention to the following configuration information, the following is the way to parse the configuration by ourselves

elasticsearch:
  host: localhost
  port: 9200
  user: elastic
  pwd: test123
  connTimeout: 3000
  socketTimeout: 5000
  connectionRequestTimeout: 500

Description

The above configuration describes a basic es document operation posture, which is more flexible to use than the better spring-boot-starter-data-elasticsearch

II. SpringBoot combined with ES

1. RestHighLevelClient initialization

Next, we operate es based on RestHighLevelClient . The first step is to initialize this instance.

@Getter
@Configuration
public class ElasticsearchConfiguration {

    @Value("${elasticsearch.host}")
    private String host;

    @Value("${elasticsearch.port}")
    private int port;

    @Value("${elasticsearch.connTimeout}")
    private int connTimeout;

    @Value("${elasticsearch.socketTimeout}")
    private int socketTimeout;

    @Value("${elasticsearch.connectionRequestTimeout}")
    private int connectionRequestTimeout;

    @Value("${elasticsearch.user}")
    private String user;

    @Value("${elasticsearch.pwd}")
    private String pwd;

    @Bean(destroyMethod = "close", name = "client")
    public RestHighLevelClient initRestClient() {
        RestClientBuilder builder = RestClient.builder(new HttpHost(host, port))
                .setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder
                        .setConnectTimeout(connTimeout)
                        .setSocketTimeout(socketTimeout)
                        .setConnectionRequestTimeout(connectionRequestTimeout));
        return new RestHighLevelClient(builder);
    }
}

Note that in the above implementation, the username + password is not used. When the username and password are set in es, authentication is performed based on the Basic Auth method in the request header for each request; it will be introduced later.

2. Basic use

We built an es on this machine for simulation testing. After the above configuration, we can directly interact with es

es installation can refer to:

The following is a simple posture to use

@Service
public class EsTest {
    @Autowired
    private RestHighLevelClient client;

    private static String auth;

    public EsTest(ElasticsearchConfiguration elasticsearchConfiguration) {
        auth = Base64Utils.encodeToString((elasticsearchConfiguration.getUser() + ":" + elasticsearchConfiguration.getPwd()).getBytes());
        auth = "Basic " + auth;
    }

    public void testGet() throws Exception {
        // 文档查询
        GetRequest getRequest = new GetRequest("first-index", "_doc", "gvarh3gBF9fSFsHNuO49");
        RequestOptions.Builder requestOptions = RequestOptions.DEFAULT.toBuilder();
        requestOptions.addHeader("Authorization", auth);
        GetResponse getResponse = client.get(getRequest, requestOptions.build());
        if (getResponse.isExists()) {
            String sourceAsString = getResponse.getSourceAsString();
            System.out.println(sourceAsString);
        } else {
            System.out.println("no string!");
        }
    }
}

Pay attention to the above implementation, there are the following important knowledge points

Authentication

The Basic Auth method is used for identity verification, which is simply to add a

  • key = Authorization
  • value = "Basic " + base64(user + ":" + pwd)

access pose

The above is an example of querying documents according to id , which can be easily understood as three steps

  • Created: XxRequest
  • Add request header: RequestOptions.Builder.addHeader
  • Execute: client.get(xxRequest, RequestOptions)

III. Source code and related knowledge points that cannot be missed

0. Project

1. WeChat public account: Yihuihui Blog

It is not as good as a letter. The above content is purely from the family. Due to limited personal ability, it is inevitable that there will be omissions and mistakes. If you find bugs or have better suggestions, you are welcome to criticize and correct them.

The following is a gray personal blog, recording all blog posts in study and work, welcome everyone to visit

一灰灰blog


hhui
一灰灰Blog的个人编程记录
248 声望
45 粉丝
0 条评论
推荐阅读
SpringBoot系列之数据库初始化-datasource配置方式
在我们的日常业务开发过程中,如果有db的相关操作,通常我们是直接建立好对应的库表结构,并初始化对应的数据,即更常见的情况下是我们在已有表结构基础之下,进行开发;但是当我们是以项目形式工作时,更常见的...

小灰灰Blog阅读 658

Spring Aop 动态代理
为了保持行为的一致性,代理类和委托类通常会实现相同的接口,所以在访问者看来两者没有丝毫的区别。通过代理类这中间一层,能有效控制对委托类对象的直接访问,也可以很好地隐藏和保护委托类对象,同时也为实施...

KerryWu5阅读 8.7k评论 1

SpringBoot集成LibreOffice+jodconverter做文件预览(office转pdf)
LibreOffice 是一款开放源代码的自由免费全能办公软件,可运行于 Microsoft Windows, GNU/Linux 以及 macOS 等操作系统上。它包含了 Writer, Calc, Impress, Draw, Math 以及 Base 等组件,可分别用于文本文档、...

Zeran2阅读 6.2k

Spring系列-实战篇(5)-数据库的事务和锁
大学里面数据库课考试,事务和锁的相关知识绝对是要划的重点。数据库的事务要遵循ACID(原子性、一致性、隔离性、持久性)四要素,锁又有悲观锁和乐观锁的划分方式。那么今天我们讲讲,如何基于SpringBoot+Mybati...

KerryWu2阅读 6k评论 1

之前很火给女朋友推送微信服务号消息是怎么做的?
经过了几天的奋战,终于把微信服务号的模板消息给写完了。后端其实没花多少时间,因为之前已经有同学提过pull request了,我在这基础之上简单优化下就完事了,主要的时间都是花在前端上,对前端页面和参数的适配...

Java3y3阅读 1.2k

简单使用spring cloud 服务注册做一个请求转发中心
背景上篇文章 记录多项目共用一个公众号逻辑修改, 实现了多个项目共用一个公众号。 但是也存在几点问题,比如:中间服务器拦截了微信的请求,虽然方便了项目不再需要写微信授权的代码,但如果以后需要再拓展新的...

weiweiyi2阅读 749

消息推送平台终于要上线啦!
我的开源项目消息推送平台Austin终于要上线了,迎来在线演示的第一版!🔥项目在线演示地址:[链接]消息推送平台🔥推送下发【邮件】【短信】【微信服务号】【微信小程序】【企业微信】【钉钉】等消息类型。[链接][链...

Java3y3阅读 1k

248 声望
45 粉丝
宣传栏