当前位置:   article > 正文

spring boot 之 整合 elastic search_elasticsearch-rest-high-level-client

elasticsearch-rest-high-level-client

本文介绍 RestHighLevelClient原生客户端 和 傻瓜级ElasticSearch搜索引擎ORM框架Easy-Es 两种方式将es集成到Spring Boot。

Spring Boot版本:2.3.12.RELEASE
ElasticSearch版本:7.14.0

原生RestHighLevelClient客户端

引入pom依赖

此处仅引入必要依赖,其余依赖按需引入。

<!--elasticsearch-->
<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>7.14.0</version>
    <exclusions>
        <exclusion>
            <artifactId>log4j-api</artifactId>
            <groupId>org.apache.logging.log4j</groupId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-client</artifactId>
    <version>7.14.0</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.14.0</version>
    <exclusions>
        <exclusion>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
        </exclusion>
        <exclusion>
            <artifactId>elasticsearch-rest-client</artifactId>
            <groupId>org.elasticsearch.client</groupId>
        </exclusion>
    </exclusions>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

application.yml配置文件

elasticsearch:
  hosts: 127.0.0.1:9200
  userName: elastic
  password: elastic
  clusterName: single-node-cluster
  connectTimeOut: 1000
  connectionRequestTimeOut: 500
  maxConnectNum: 100
  maxConnectNumPerRoute: 100
  scheme: http
  socketTimeOut: 30000
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

Elasticsearch配置类

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * restHighLevelClient 客户端配置类
 */
@Slf4j
@Data
@Configuration
@ConfigurationProperties(prefix = "elasticsearch")
public class ElasticsearchConfig {

    // es host ip 地址(集群)
    private String hosts;
    // es 用户名
    private String userName;
    // es 密码
    private String password;
    // es 请求方式
    private String scheme;
    // es 集群名称
    private String clusterName;
    // es 连接超时时间
    private int connectTimeOut;
    // es socket 连接超时时间
    private int socketTimeOut;
    // es 请求超时时间
    private int connectionRequestTimeOut;
    // es 最大连接数
    private int maxConnectNum;
    // es 每个路由的最大连接数
    private int maxConnectNumPerRoute;

    /**
     * 如果@Bean没有指定bean的名称,那么这个bean的名称就是方法名
     */
    @Bean(name = "restHighLevelClient")
    public RestHighLevelClient restHighLevelClient() {
        RestHighLevelClient restHighLevelClient = null;
        try {
            // 集群,拆分地址
            List<HttpHost> hostLists = new ArrayList<>();
            String[] hostList = hosts.split(",");
            for (String addr : hostList) {
                String host = addr.split(":")[0];
                String port = addr.split(":")[1];
                hostLists.add(new HttpHost(host, Integer.parseInt(port), scheme));
            }
            // 转换成 HttpHost 数组
            HttpHost[] httpHost = hostLists.toArray(new HttpHost[]{});
            // 构建连接对象
            RestClientBuilder builder = RestClient.builder(httpHost);
            // 设置用户名、密码
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
            // 连接延时配置
            builder.setRequestConfigCallback(requestConfigBuilder -> {
                requestConfigBuilder.setConnectTimeout(connectTimeOut);
                requestConfigBuilder.setSocketTimeout(socketTimeOut);
                requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeOut);
                return requestConfigBuilder;
            });
            // 连接数配置
            builder.setHttpClientConfigCallback(httpClientBuilder -> {
                httpClientBuilder.setMaxConnTotal(maxConnectNum);
                httpClientBuilder.setMaxConnPerRoute(maxConnectNumPerRoute);
                httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                return httpClientBuilder;
            });
            restHighLevelClient = new RestHighLevelClient(builder);
        } catch (NumberFormatException e) {
            log.error("ES 连接池初始化异常");
        }
        return restHighLevelClient;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90

整合easy-es

Easy-ES官方地址 https://www.easy-es.cn/

引入pom依赖

此处仅引入必要依赖,其余依赖按需引入。

<!--spring-boot-starter-web-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <!--排除spring-boot自带的es依赖-->
    <exclusions>
        <exclusion>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<!--elasticsearch-->
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.14.0</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>7.14.0</version>
</dependency>
<dependency>
    <groupId>org.dromara.easy-es</groupId>
    <artifactId>easy-es-boot-starter</artifactId>
    <version>2.0.0-beta8</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

application.yml配置文件

此处仅做基础配置,详细配置见官方文档。

easy-es:
  banner: false
  address: 127.0.0.1:9200
  username: elastic
  password: elastic
  • 1
  • 2
  • 3
  • 4
  • 5

新建实体类

import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.dromara.easyes.annotation.IndexName;

import java.io.Serializable;

@Getter
@Setter
@Accessors(chain = true)
@IndexName
public class Student implements Serializable {

    private static final long serialVersionUID = 1L;

    // @IndexId(type = IdType.CUSTOMIZE)
    private String id;

    private String studentName;

    private int age;

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

新建mapper层

注意:easy-es的操作与Mybatis-Plus十分类似,项目中若引用了Mybatis-Plus,不要引错包。

import org.dromara.easyes.core.kernel.BaseEsMapper;

public interface StudentMapper extends BaseEsMapper<Student> {
}
  • 1
  • 2
  • 3
  • 4

新建测试类

该测试只是简单的测试了部分方法,更多操作详见官方文档。

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSONObject;

import org.dromara.easyes.core.conditions.select.LambdaEsQueryWrapper;
import org.junit.Test;
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.util.List;

@SpringBootTest
@RunWith(SpringRunner.class)
public class EsTest {

    @Autowired
    private StudentMapper studentMapper;

    // 根据实体类创建索引
    // 默认是1分片1备份,更加详细的索引创建可参考官方文档 目录:索引CRUD
    @Test
    public void createIndex() {
        studentMapper.createIndex();
    }

    // 添加数据,数据id默认自动生成,若想自定义参考官方文档 目录:注解 @IndexId
    @Test
    public void addData() {
        Student student = new Student();
        student.setId("2");
        student.setStudentName("王五");
        student.setAge(20);
        Integer insert = studentMapper.insert(student);
        System.err.println(insert);
    }

    // 查询数据
    @Test
    public void getData() {
        LambdaEsQueryWrapper<Student> queryWrapper = new LambdaEsQueryWrapper<>();
        queryWrapper.eq(Student::getStudentName, "张三");
        Student student = studentMapper.selectOne(queryWrapper);
        System.err.println(JSONObject.toJSONString(student));
    }

    // 更新数据
    @Test
    public void updateData01() {
        int age = 20;
        Student student = new Student();
        student.setId("1");
        student.setAge(age);
        System.err.println(studentMapper.updateById(student));
    }

    // 更新数据
    @Test
    public void updateData02() {
        LambdaEsQueryWrapper<Student> queryWrapper = new LambdaEsQueryWrapper<>();
        queryWrapper.eq(Student::getId, "1");
        Student student = new Student();
        student.setId("1");
        student.setAge(18);
        System.err.println(studentMapper.update(student, queryWrapper));
    }

    // 查询所有数据
    @Test
    public void getAllData() {
        LambdaEsQueryWrapper<Student> queryWrapper = new LambdaEsQueryWrapper<>();
        List<Student> list = studentMapper.selectList(queryWrapper);
        list.forEach(student -> System.out.println(student.getStudentName() + " == " + student.getAge() + " == " + student.getId()));
    }

    // 根据id批量删除数据
    @Test
    public void deleteAllData() {
        Integer i = studentMapper.deleteBatchIds(CollUtil.newArrayList("1", "2"));
        System.err.println(i);
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号