springboot 整合 elasticsearch7.0+

说明

elasticsearch官网Java API文档说明。 如果是引入 spring-boot-starter-data-elasticsearch,这个是不支持7.0 + 版本的,而且很多用法过时,甚至后面的版本弃用了。如下图所示:
springboot 整合 elasticsearch7.0+
按照官网,我们用高级REST客户端,闲话少叙,开干。

springboot 整合 elasticsearch

引入 pom 依赖

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>cn.com.es</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>elasticsearch</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

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

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.8.0</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.8.0</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.76</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

application.yml

spring:
  application:
    name: elasticsearch-app

server:
  port: 8888

编写配置类

swagger 配置

package cn.com.es.elasticsearch.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("cn.com.es.elasticsearch"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("swagger-bootstrap-ui RestFul APIs")
                .description("swagger-bootstrap-ui")
                .version("1.1")
                .build();
    }

}

elasticsearch 配置

package cn.com.es.elasticsearch.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticsearchConfig {
    //创建单例请求
    //官网:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.6/java-rest-low-usage-requests.html#java-rest-low-usage-request-options
    public static final RequestOptions COMMON_OPTIONS;

    static {
        RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
        COMMON_OPTIONS = builder.build();
    }

    // 创建连接
    // https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.6/java-rest-high-getting-started-initialization.html
    @Bean
    public RestHighLevelClient elasticsearchClient() {
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("192.168.150.128", 9200, "http")
                )
        );
        return client;
    }
}

准备工作

准备两个 vo ,便于测试

ResultVo.java

package cn.com.es.elasticsearch.vo;

import lombok.Data;

@Data
public class ResultVo<T> {
    private static final String SUCCESS_CODE = "S10000";
    private static final String UNKNOWN_FAIL_CODE = "E10001";

    private T data;
    private String code;
    private String message;
    private boolean success;

    public ResultVo() {
    }

    public ResultVo(boolean success, String code) {
        this.success = success;
        this.code = code;
    }

    public ResultVo(T data, boolean success, String code, String message) {
        this.data = data;
        this.success = success;
        this.code = code;
        this.message = message;
    }

    public static ResultVo<Void> success() {
        return success(null, (String)null);
    }

    public static <R> ResultVo<R> success(R data) {
        return success(data, (String)null);
    }

    public static <R> ResultVo<R> success(R data, String message) {
        return new ResultVo(data, true, SUCCESS_CODE, message);
    }

    public static ResultVo<Void> successMsg(String message) {
        return success(null, message);
    }

    public static <R> ResultVo<R> failure(String code) {
        return failure(code, (String)null);
    }

    public static <R> ResultVo<R> failure(String code, String message) {
        return failure(null, code, message);
    }

    public static <R> ResultVo<R> failure(R data, String code, String message) {
        return new ResultVo(data, false, code, message);
    }

    public static <R> ResultVo<R> failureMsg(String message) {
        return failure(UNKNOWN_FAIL_CODE, message);
    }

}

UserVo.java

package cn.com.es.elasticsearch.vo;

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

@Data
public class UserVo {

    private Long id;

    private String userName;

    private String sex;

    private String job;

    private Double salary;

    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date birthday;

}

创建索引

创建一个 controller 测试创建索引

package cn.com.es.elasticsearch.web;

import cn.com.es.elasticsearch.config.ElasticsearchConfig;
import cn.com.es.elasticsearch.vo.ResultVo;
import cn.com.es.elasticsearch.vo.UserVo;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@Log4j2
@Api(tags = "elasticsearch测试")
@RestController
@RequestMapping("/elasticsearch")
public class ElasticsearchController {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 创建索引:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.6/java-rest-high-document-index.html
     * @param userVo
     * @return
     */
    @ApiOperation(value = "创建索引")
    @PostMapping("/createIndex")
    public ResultVo createIndex(@RequestBody UserVo userVo) throws IOException {
        IndexRequest indexRequest = new IndexRequest("users");
        indexRequest.id("1");
        String jsonString = JSONObject.toJSONString(userVo);
        //要保存的内容
        indexRequest.source(jsonString, XContentType.JSON);
        //执行操作
        IndexResponse index = client.index(indexRequest, ElasticsearchConfig.COMMON_OPTIONS);

        log.info("响应数据:{}", index);
        return ResultVo.successMsg("索引创建成功");
    }
}

swagger 响应结果
springboot 整合 elasticsearch7.0+
springboot 整合 elasticsearch7.0+

上一篇:springboot+vue计算机毕业设计javaweb在线考试系统设计与实现web(含源码及数据库文件)


下一篇:什么是响应式编程,Java 如何实现