spring boot 集成 elastic search

参考文档 spring boot 官方文档

elastic search 更新的很快,不管是国内的还是国外的网上的好多教程都是比较老的版本,好多类和方法都被废弃了。找了个 spring boot 官方的教程中途还报错了,后来根据报错信息结合 spring-boot-autoconfigure jar 包里的源码找到了解决办法。

源码可以在 github 下载。

1. 添加依赖



<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>

    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.3.1.RELEASEversion>
        <relativePath/> 
    parent>

    <groupId>org.examplegroupId>
    <artifactId>spring-boot-esartifactId>
    <version>1.0-SNAPSHOTversion>

    <properties>
        <java.version>1.8java.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-elasticsearchartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-validationartifactId>
        dependency>

        <dependency>
            <groupId>javax.validationgroupId>
            <artifactId>validation-apiartifactId>
            <version>1.1.0.Finalversion>
        dependency>


        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>

        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
        dependency>


    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>

    <repositories>
        <repository>
            <id>spring-milestonesid>
            <name>Spring Milestonesname>
            <url>https://repo.spring.io/milestoneurl>
        repository>
        <repository>
            <id>spring-snapshotsid>
            <name>Spring Snapshotsname>
            <url>https://repo.spring.io/snapshoturl>
            <snapshots>
                <enabled>trueenabled>
            snapshots>
        repository>
    repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-milestonesid>
            <name>Spring Milestonesname>
            <url>https://repo.spring.io/milestoneurl>
        pluginRepository>
        <pluginRepository>
            <id>spring-snapshotsid>
            <name>Spring Snapshotsname>
            <url>https://repo.spring.io/snapshoturl>
            <snapshots>
                <enabled>trueenabled>
            snapshots>
        pluginRepository>

    pluginRepositories>


project>

2. 定义 spring boot 的启动类

package demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @Author:shifengqiang
 * @Date:2020/7/30 3:42 下午
 */
@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

3. 定义 User 类

package demo.document;

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;

/**
 * @Author:shifengqiang
 * @Date:2020/7/30 4:31 下午
 */
@Document(indexName = "users")
@Data
public class User {
    @Id
    private Long id;
    private String name;
    private Integer age;
}

4. 定义 ElasticSearchConfig 类。

package demo.config;

import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.config.ElasticsearchConfigurationSupport;

/**
 * @Author:shifengqiang
 * @Date:2020/7/30 3:59 下午
 */
@Configuration
public class ElasticSearchConfig extends ElasticsearchConfigurationSupport {
    @Value("${es_host}")
    private String esHost;

    @Value("${es_port}")
    private String esPort;

    @Bean
    public RestHighLevelClient elasticsearchClient() {
        ClientConfiguration.ClientConfigurationBuilderWithRequiredEndpoint builder = ClientConfiguration.builder();
        final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                .connectedTo(esHost + ":" + esPort)
                .build();

        return RestClients.create(clientConfiguration).rest();
    }
}

在这一步中,官方给的例子是有问题的,我是根据报错提示并结合 spring-boot-autoconfigure 里的源码找到解决办法的,最近在读 rocketmq 的源码,详细过程就不写了,如果大家在集成的过程中遇到问题可以给我留言。

5. 定义 UserController 。

package demo.controller;

import demo.document.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author:shifengqiang
 * @Date:2020/7/30 5:50 下午
 */
@RestController
public class UserController {
    @Autowired
    private ElasticsearchRestTemplate elasticsearchTemplate;

    @RequestMapping("/query")
    @ResponseBody
    public User queryUser() {
        User user = elasticsearchTemplate
                .get("3", User.class);
        return user;
    }
    @RequestMapping("/save")
    @ResponseBody
    public User saveUser() {
        User user = new User();
        user.setId(3L);
        user.setAge(3223);
        user.setName("shifengqiang3");


        IndexCoordinates indexOperations = IndexCoordinates.of("users");

        IndexQuery indexQuery = new IndexQueryBuilder()
                .withId("3")
                .withObject(user)
                .build();
        String documentId = elasticsearchTemplate.index(indexQuery, indexOperations);

        return user;
    }
}

6. 在 application.properties 添加 es 的 ip 地址和端口号。

server.port=8080
es_host=localhost
es_port=9200

到此就完成了,可以打开浏览器测试了。

你可能感兴趣的:(elasticserach,spring,boot)