springboot简易集成ElasticSearch

写在前面:本文将搭建的ElasticSearch环境采用单机单节点方式,如果读者想采用集群方式请移步至https://blog.csdn.net/belonghuang157405/article/details/83301937

Elasticsearch: 权威指南 : https://www.elastic.co/guide/cn/elasticsearch/guide/current/index.html

代码示例地址:https://github.com/Blankwhiter/elasticsearch

一、ElasticSearch环境搭建

1.在centos窗口中,执行如下命令:

docker pull elasticsearch:5.6.8

当前ES镜像版本信息:

 {
  "name" : "WlwFyqU",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "78UDZtviQqiWmzmenGpSrQ",
  "version" : {
    "number" : "5.6.8",
    "build_hash" : "cfe3d9f",
    "build_date" : "2018-09-10T20:12:43.732Z",
    "build_snapshot" : false,
    "lucene_version" : "6.6.1"
  },
  "tagline" : "You Know, for Search"
 }

2.创建数据挂在目录,以及配置ElasticSearch集群配置文件,调高JVM线程数限制数量

  • 1.创建数据文件挂载目录data
    在centos窗口中,执行如下操作:
[root@localhost soft]# pwd
/home/soft/ES
[root@localhost ES]# mkdir data
[root@localhost ES]# cd ES/config/
  • 2.在centos窗口中,使用vim命令分别创建es.yml文件
    es.yml
cluster.name: elasticsearch-single
node.name: es-node
network.bind_host: 0.0.0.0
network.publish_host: 192.168.9.219
http.port: 9204
transport.tcp.port: 9304
http.cors.enabled: true
http.cors.allow-origin: "*"
node.master: true 
node.data: true  

注:读者根据自身配置修改network.publish_host、http.port、transport.tcp.port

  • 3.调高JVM线程数限制数量
    在centos窗口中,修改配置sysctl.conf
vim /etc/sysctl.conf

加入如下内容:

vm.max_map_count=262144 

启用配置:

sysctl -p

注:这一步是为了防止启动容器时,报出如下错误:
bootstrap checks failed max virtual memory areas vm.max_map_count [65530] likely too low, increase to at least [262144]

3.启动ElasticSearch容器

docker run -e ES_JAVA_OPTS="-Xms256m -Xmx256m" -d -p 9204:9204 -p 9304:9304 -v /home/soft/ES/config/es.yml:/usr/share/elasticsearch/config/elasticsearch.yml -v /home/soft/ES/data:/usr/share/elasticsearch/data --name ES-single elasticsearch:5.6.8

三、spring boot集成ElasticSearch

集成文档:https://github.com/spring-projects/spring-data-elasticsearch
由于本文中使用的ElasticSearch是5.6.8 故选择的spring data elasticsearch 版本是3.0.X,请参考附录1
1.引入环境所需的jar 以及配置
pom.xml

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

    <groupId>com.elasticsearch</groupId>
    <artifactId>springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springboot</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <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-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--版本3.0.11.RELEASE-->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-elasticsearch</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.2</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

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


</project>

application.yml

spring:
  data:
    elasticsearch:
      cluster-name: elasticsearch-single
      cluster-nodes: 192.168.9.219:9304

2.编写实体以及repository类
Book.java

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

@Data
@Document(indexName = "kind",type = "book")
public class Book {

    /**
     * 主键
     */
    private Integer id;

    /**
     * 作者
     */
    private String author;

    /**
     * 书名
     */
    private String bookName;

    /**
     * 描述
     */
    private String desc;
}

BookRepository.java

import com.elasticsearch.springboot.po.Book;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Component;

@Component
public interface BookRepository extends ElasticsearchRepository<Book,Integer> {
}

3.测试

import com.elasticsearch.springboot.po.Book;
import com.elasticsearch.springboot.repository.BookRepository;
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.Optional;

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


    @Autowired
    BookRepository bookRepository;

    /**
     * 创建索引
     */
    @Test
    public void createIndex(){
        Book book = new Book();
        book.setId(1);
        book.setAuthor("周志明");
        book.setBookName("深入理解Java虚拟机_JVM高级特性与最佳实践");
        book.setDesc("Java虚拟机,最佳实践。。。。");
        bookRepository.save(book);
    }

    /**
     * 搜索索引
     */
    @Test
    public void searchIndex(){
        Optional<Book> optionalBook = bookRepository.findById(1);
        System.out.println(optionalBook.get().toString());
    }


    @Test
    public void contextLoads() {
    }

}

这里就简单举了创建以及搜索索引,其他请读者自行看文档学习。

四、额外一种:JestClient操作ElasticSearch

jest文档:https://github.com/searchbox-io/Jest/tree/master/jest

1.引入环境所需的jar 以及配置
pom.xml

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

    <groupId>com.elasticsearch</groupId>
    <artifactId>jest</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>jest</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <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-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.searchbox</groupId>
            <artifactId>jest</artifactId>
            <version>5.3.3</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.2</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

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


</project>

application.yml

spring:
  elasticsearch:
    jest:
      uris: http://192.168.9.219:9204

2.编写实体类
Article.java

import io.searchbox.annotations.JestId;
import lombok.Data;

/**
 * 文章实体类
 */
@Data
public class Article {

    /**
     * 主键
     */
    @JestId
    private Integer id;
    /**
     * 作者
     */
    private String author;

    /**
     * 标题
     */
    private String title;

    /**
     * 内容
     */
    private String content;

}

3.测试

import com.elasticsearch.jest.po.Article;
import io.searchbox.client.JestClient;
import io.searchbox.core.Index;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
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.io.IOException;

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

    /**
     * 引入
     */
    @Autowired
    JestClient jestClient;


    /**
     * 创建索引
     */
    @Test
    public void createIndex() {
        Article article = new Article();
        article.setId(1);
        article.setAuthor("海子");
        article.setTitle("面朝大海,春暖花开");
        article.setContent("从明天起,做一个幸福的人。。。。。。");

        Index index = new Index.Builder(article).index("article").type("poetry").build();
        try {
            jestClient.execute(index);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 搜索索引
     * @throws IOException
     */
    @Test
    public void searchIndex() throws IOException {
        StringBuffer query  = new StringBuffer("{\n" +
                "    \"query\" : {\n" +
                "        \"match\" : {\n" +
                "            \"content\" : \"明天\"\n" +
                "        }\n" +
                "    }\n" +
                "}");
        Search search = new Search.Builder(query.toString()).addIndex("article").addType("poetry").build();
        SearchResult result = jestClient.execute(search);
        System.out.println(result+" : "+result.getJsonString());
    }


    @Test
    public void contextLoads() {
    }

}

更多内容,请移步至文档学习。

附录:

1.spring data elasticsearch 对应ElasticSearch版本

spring data elasticsearch Elasticsearch Version
3.1.x 6.2.2
3.0.x 5.5.0
2.1.x 2.4.0
2.0.x 2.2.0
1.3.x 1.5.2
2.jest对应ElasticSearch版本
Jest Version Elasticsearch Version
>= 6.0.0 6
>= 5.0.0 5
>= 2.0.0 2
0.1.0 - 1.0.0 1
<= 0.0.6 < 1

猜你喜欢

转载自blog.csdn.net/belonghuang157405/article/details/83338684