原创 | 一篇解决Springboot 整合 Elasticsearch

  • 2020 年 1 月 14 日
  • 筆記

大家好,我是润森。期末已挂,谁来烧纸。

昨天我发现IDEA过期了,十分钟解决了。公众号回复 IDEA就ok

ElasticSearch

结合业务的场景,在目前的商品体系需要构建搜索服务,主要是为了提供用户更丰富的检索场景以及高速,实时及性能稳定的搜索服务。

ElasticSearch是一个基于Lucene的搜索服务器,其实就是对Lucene进行封装,提供了RESTAPI 的操作接口。

ElasticSearch作为一个高度可拓展的开源全文搜索和分析引擎,可用于快速地对大数据进行存储,搜索和分析。

ElasticSearch主要特点:分布式、高可用、异步写入、多API、面向文档 。

ElasticSearch核心概念:近实时,集群,节点(保存数据),索引,分片(将索引分片),副本(分片可设置多个副本) 。它可以快速地储存、搜索和分析海量数据。

Docker搭建 Elasticsearch

安装Elasticsearch的Docker镜像

目前Elasticsearch 版本到了7.X, Springboot 目前不支持7.X以上的elasticsearch。所以还是选择了稳定的2.4.6

ubuntu@VM-0-5-ubuntu:~$ docker pull elasticsearch:2.4.6  2.4.6: Pulling from library/elasticsearch  05d1a5232b46: Already exists  5cee356eda6b: Already exists  89d3385f0fd3: Already exists  65dd87f6620b: Already exists  78a183a01190: Already exists  1a4499c85f97: Already exists  2c9d39b4bfc1: Already exists  1b1cec2222c9: Already exists  59ff4ce9df68: Already exists  1976bc3ee432: Already exists  a27899b7a5b5: Already exists  b0fc7d2c927a: Already exists  6d94b96bbcd0: Already exists  6f5bf40725fd: Already exists  2bf2a528ae9a: Already exists  Digest: sha256:41ed3a1a16b63de740767944d5405843db00e55058626c22838f23b413aa4a39  Status: Downloaded newer image for elasticsearch:2.4.6  docker.io/library/elasticsearch:2.4.6  ubuntu@VM-0-5-ubuntu:~$ docker run -d -p 9200:9200 -p 9300:9300 --name elasticsearch elasticsearch:2.4.6  # 如果跑不了,与服务器的内存有关  ubuntu@VM-0-5-ubuntu:~$ docker run -e ES_JAVA_OPIS="-Xms256m -Xmx256m" -d -p 9200:9200  -p 9300:9300 --name elasticsearch elasticsearch:2.4.6  4e54a696130f92c7a94835313a36e359e51cf02f08e85fc281667e4a238cf5e9

访问服务器的9200端口,测试是否成功搭建Elasticsearch

springboot搭建 Elasticsearch工程

选择NOSQL中的 Elasticsearch依赖

pom.xml项目配置依赖

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

SpringBoot默认支持两种技术来和ES交互

  1. Jest(默认不生效)

需要导入jest的工具包(io.searchbox.client.JestClient)

  1. SpringData ElasticSearch【ES版本有可能不合适】

Jest

Jest是Elasticsearch 的Java Http Rest 客户端。

ElasticSearch已经具备应用于Elasticsearch内部的Java API,但是Jest弥补了ES自有API缺少Elasticsearch Http Rest接口客户端的不足。

去maven仓库搜jest

链接: https://mvnrepository.com/artifact/io.searchbox/jest

记得在pom文件中引入jest,先注释掉ElasticSearch的依赖:

<!--        <dependency>-->  <!--            <groupId>org.springframework.boot</groupId>-->  <!--            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>-->  <!--        </dependency>-->            <!-- https://mvnrepository.com/artifact/io.searchbox/jest -->          <dependency>              <groupId>io.searchbox</groupId>              <artifactId>jest</artifactId>              <version>2.4.0</version>          </dependency>

Jest使用默认配置JestAutoConfiguration,而JestAutoConfiguration注入一个JestClient,要使用这个客户端,要先在配置文件中指定es的地址:

application.properties配置文件

spring.elasticsearch.jest.uris=http://ip:9200

跑起来看看是否连接成功

Jest实战演练

创建bean.Article类,私有变量id, author,title,content,补充Getter和Setter

@JestId

import io.searchbox.annotations.JestId;  /**   * @author: 毛利   */  public class Article {        @JestId      private Integer id;      private String author;      private String title;      private String content;        public Integer getId() {          return id;      }        public void setId(Integer id) {          this.id = id;      }        public String getAuthor() {          return author;      }        public void setAuthor(String author) {          this.author = author;      }        public String getTitle() {          return title;      }        public void setTitle(String title) {          this.title = title;      }        public String getContent() {          return content;      }        public void setContent(String content) {          this.content = content;      }  }  

ElasticsearchApplicationTests测试类中

@Autowired  JestClient jestClient;    @Test  void contextLoads() {      // 给Es中索引(保存)一个文档;      Article article = new Article();      article.setId(1);      article.setTitle("好消息");      article.setAuthor("zhangsan");      article.setContent("Hello World");      // 构建一个索引功能      Index index = new Index.Builder(article).index("atguigu").type("news").build();      try {          jestClient.execute(index);      } catch (IOException e) {          e.printStackTrace();      }  }

运行测试,访问http://ip:9200/atguigu/news/1

测试搜索

@Test  void search() {        //查询表达式  content有hello      String json = "{n" +              "    "query" : {n" +              "        "match" : {n" +              "            "content" : "hello"n" +              "        }n" +              "    }n" +              "}";          //构建搜索功能      Search search = new Search.Builder(json).addIndex("atguigu").addType("news").build();        //执行      try {          SearchResult result = jestClient.execute(search);          System.out.println(result.getJsonString());      } catch (IOException e) {          e.printStackTrace();      }  }

更多操作:https://github.com/searchbox-io/Jest/tree/master/jest

测试运行

运行如下

SpringData ElasticSearch

还有一个SpringData ElasticSearch

pom文件打开SpringData ElasticSearch依赖

注意Elasticsearchspring-boot-starter-data-elasticsearch版本对应

新新版本的SpringBoot 2spring-boot-starter-data-elasticsearch中支持的Elasticsearch版本是2.X, 但Elasticsearch实际上已经发展到6.5.X版本了,为了更好的使用Elasticsearch的新特性, 所以弃用了spring-boot-starter-data-elasticsearch依赖,而改为直接使用Spring-data-elasticsearch

Docker安装Elasticsearch镜像6.X,和上面一样

docker pull elasticsearch:6.8.6  # 加速  docker pull registry.docker-cn.com/library/elasticsearch:6.8.6  docker run -d -p 9201:9200 -p 9301:9300 --name elasticsearch elasticsearch:6.8.6  # 我发现内存空间不够,好像很多人死在那  docker run --name elasticsearch -d -e ES_JAVA_OPTS="-Xms128m -Xmx128m"  -e "discovery.type=single-node" -p 9201:9200 -p 9301:9300 elasticsearch:6.8.6

访问测试OK

docker-cluster这里创建一个容器变了

application.properties配置文件

spring.data.elasticsearch.cluster-name=docker-cluster  spring.data.elasticsearch.cluster-nodes=ip:9301

跑起来测试下

SpringData ElasticSearch就是编写一个ElasticsearchRepository 的子接口来操作ES

SpringData ElasticSearch实战演练

新建bean.Book类,三个类变量,补充GetterSetter

ElasticSearch是面对文档的

@Document(indexName = "atguigu", type = "book")补充文档:index序列和type

import org.springframework.data.elasticsearch.annotations.Document;  /**   * @author: 毛利   */  @Document(indexName = "atguigu", type = "book")  public class Book {      private Integer id;      private String bookName;        private String author;        public Integer getId() {          return id;      }        public void setId(Integer id) {          this.id = id;      }        public String getBookName() {          return bookName;      }        public void setBookName(String bookName) {          this.bookName = bookName;      }        public String getAuthor() {          return author;      }        public void setAuthor(String author) {          this.author = author;      }        @Override      public String toString() {          return "Book{" +                  "id=" + id +                  ", bookName='" + bookName + ''' +                  ", author='" + author + ''' +                  '}';      }  }  

编写repository.BookRepository接口继承ElasticsearchRepository接口

同时重写findByBookNameLike`方法

import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;  import java.util.List;    /**   * @author: 毛利   */  public interface BookRepository extends ElasticsearchRepository<Book, Integer> {      public List<Book> findByBookNameLike(String bookName);  }

测试类

@Autowired  BookRepository bookRepository;    @Test  public void test02() {  	Book book = new Book();  	book.setId(1);  	book.setBookName("西游记");  	book.setAuthor("吴承恩");  	bookRepository.index(book);  }

运行测试类后,访问是否找到book1

@Test  public void test02() {  //		Book book = new Book();  //		book.setId(1);  //		book.setBookName("西游记");  //		book.setAuthor("吴承恩");  //		bookRepository.index(book);      // 测试是否通过findByBookNameLike的模糊查询找到西游记      for (Book book : bookRepository.findByBookNameLike("游")) {          System.out.println(book);      }    }

总结

本文通过两种方法实现对Springboot整合ElasticSearch

希望以上对你学习有用

再自我介绍一下吧。我叫润森,是一个的学习者。