SpringBoot 整合 elasticsearch 实例

avatar 2018年01月22日21:02:21 10 6414 views
博主分享免费Java教学视频,B站账号:Java刘哥
上一篇文章介绍了安装 mac 上安装 elasticsearch 本文介绍 SpringBoot 集成 elasticsearch  

一、下载 并启动 elasticsearch

下载地址:https://www.elastic.co/downloads/past-releases 选择一个版本,下载 博主这里测试使用的是 2.4.4 下载方式可以选择 ZIP 包   启动的话,windows 和 mac 有些细微区别 windows :进入文件目录下的 bin,然后点击 elasticsearch.bat 即可 mac:在终端执行命令 bin/elasticsearch    

二、配置 Maven

  1. <!-- Spring Boot Elasticsearch 依赖 -->
  2. <dependency>
  3.    <groupId>org.springframework.boot</groupId>
  4.    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
  5. </dependency>
 
  1. <properties>
  2.    <elasticsearch.version>2.4.4</elasticsearch.version>
  3. </properties>
    添加 spring-boot-starter-data-elasticsearch 依赖,并设置 elasticsearch 版本为 2.4.4   ES 和 SpirngBoot 版本参考: https://github.com/spring-projects/spring-data-elasticsearch/wiki/Spring-Data-Elasticsearch---Spring-Boot---version-matrix  

三、修改 application.properties

  1. #Project
  2. server.port=8080
  3. debug=true
  4. server.context-path=/chuyun
  5. # DataSource
  6. spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  7. spring.datasource.username=root
  8. spring.datasource.password=123456
  9. spring.datasource.url=jdbc:mysql://localhost:3306/chuyun?characterEncodeing=utf-8&useSSL=false
  10. # JPA
  11. spring.jpa.show-sql=true
  12. spring.jpa.hibernate.ddl-auto=update
  13. #Thymeleaf
  14. spring.thymeleaf.encoding=UTF-8
  15. spring.thymeleaf.cache=false
  16. spring.thymeleaf.cache-period=0
  17. spring.template.cache=false
  18. spring.thymeleaf.mode=HTML5
  19. spring.thymeleaf.prefix=classpath:templates/
  20. spring.thymeleaf.suffix=.html
  21. #Elasticsearch
  22. spring.data.elasticsearch.cluster-nodes=localhost:9300
  23. spring.data.elasticsearch.properties.transport.tcp.connect_timeout=120s
主要是添加最后面两条  

四、创建 ES Bean 和 Repository

Article.java
  1. package com.liuyanzhao.chuyun.domain.es;
  2. import org.springframework.data.elasticsearch.annotations.Document;
  3. import javax.persistence.Id;
  4. import java.util.Date;
  5. /**
  6.  * @author 言曌
  7.  * @date 2018/1/22 下午4:45
  8.  */
  9. @Document(indexName="chuyun",type="article",indexStoreType="fs",shards=5,replicas=1,refreshInterval="-1")
  10. public class Article {
  11.     //文章ID,这里必须为 id
  12.     @Id
  13.     private Long id;
  14.     //标题
  15.     private String title;
  16.     //内容
  17.     private String content;
  18.     //浏览量
  19.     private Integer viewCount;
  20.     //发布时间
  21.     private Date createTime;
  22.     //更新时间
  23.     private Date updateTime;
  24.     public Article() {
  25.     }
  26.     public Long getId() {
  27.         return id;
  28.     }
  29.     public void setId(Long id) {
  30.         this.id = id;
  31.     }
  32.     public String getTitle() {
  33.         return title;
  34.     }
  35.     public void setTitle(String title) {
  36.         this.title = title;
  37.     }
  38.     public String getContent() {
  39.         return content;
  40.     }
  41.     public void setContent(String content) {
  42.         this.content = content;
  43.     }
  44.     public Integer getViewCount() {
  45.         return viewCount;
  46.     }
  47.     public void setViewCount(Integer viewCount) {
  48.         this.viewCount = viewCount;
  49.     }
  50.     public Date getCreateTime() {
  51.         return createTime;
  52.     }
  53.     public void setCreateTime(Date createTime) {
  54.         this.createTime = createTime;
  55.     }
  56.     public Date getUpdateTime() {
  57.         return updateTime;
  58.     }
  59.     public void setUpdateTime(Date updateTime) {
  60.         this.updateTime = updateTime;
  61.     }
  62.     @Override
  63.     public String toString() {
  64.         return "Article{" +
  65.                 "id=" + id +
  66.                 ", title='" + title + '\'' +
  67.                 ", content='" + content + '\'' +
  68.                 ", viewCount=" + viewCount +
  69.                 ", createTime=" + createTime +
  70.                 ", updateTime=" + updateTime +
  71.                 '}';
  72.     }
  73. }
  ArticleRepository.java
  1. package com.liuyanzhao.chuyun.repository.es;
  2. import com.liuyanzhao.chuyun.domain.es.Article;
  3. import org.springframework.data.domain.Page;
  4. import org.springframework.data.domain.Pageable;
  5. import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
  6. /**
  7.  * @author 言曌
  8.  * @date 2018/1/22 下午5:05
  9.  */
  10. public interface ArticleRepository extends ElasticsearchRepository<Article, Long> {
  11.     Page<Article> findDistinctByTitleContainingOrContentContaining(String title, String content, Pageable pageable);
  12. }
   

五、创建测试类

ArticleRepositoryTest.java
  1. package com.liuyanzhao.chuyun.repository.es;
  2. import com.liuyanzhao.chuyun.domain.es.Article;
  3. import com.liuyanzhao.chuyun.entity.User;
  4. import org.junit.Before;
  5. import org.junit.Test;
  6. import org.junit.runner.RunWith;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.boot.test.context.SpringBootTest;
  9. import org.springframework.data.domain.Page;
  10. import org.springframework.data.domain.PageRequest;
  11. import org.springframework.data.domain.Pageable;
  12. import org.springframework.test.context.junit4.SpringRunner;
  13. import java.util.Date;
  14. /**
  15.  * @author 言曌
  16.  * @date 2018/1/21 下午5:03
  17.  */
  18. @RunWith(SpringRunner.class)
  19. @SpringBootTest
  20. public class ArticleRepositoryTest {
  21.     @Autowired
  22.     private ArticleRepository articleRepository;
  23.     @Before
  24.     public void initRepositoryData() {
  25.         //清除所有数据
  26.         articleRepository.deleteAll();
  27.         Article article = new Article();
  28.         article.setId((long1);
  29.         article.setTitle("《蝶恋花》");
  30.         article.setContent("槛菊愁烟兰泣露,罗幕轻寒,燕子双飞去。明月不谙离恨苦,斜光到晓穿朱户。昨夜西风凋碧树,独上高楼,望尽天涯路。欲寄彩笺兼尺素,山长水阔知何处?");
  31.         article.setCreateTime(new Date());
  32.         article.setUpdateTime(new Date());
  33.         article.setViewCount(678);
  34.         articleRepository.save(article);
  35.         Article article2 = new Article();
  36.         article2.setId((long2);
  37.         article2.setTitle("《蝶恋花》");
  38.         article2.setContent("伫倚危楼风细细,望极春愁,黯黯生天际。草色烟光残照里,无言谁会凭阑意。拟把疏狂图一醉,对酒当歌,强乐还无味。衣带渐宽终不悔,为伊消得人憔悴。");
  39.         article2.setCreateTime(new Date());
  40.         article2.setUpdateTime(new Date());
  41.         article.setViewCount(367);
  42.         articleRepository.save(article2);
  43.         Article article3 = new Article();
  44.         article3.setId((long3);
  45.         article3.setTitle("《青玉案·元夕》");
  46.         article3.setContent("东风夜放花千树,更吹落,星如雨。宝马雕车香满路。凤箫声动,玉壶光转,一夜鱼龙舞。蛾儿雪柳黄金缕,笑语盈盈暗香去。众里寻他千百度,蓦然回首,那人却在,灯火阑珊处。");
  47.         article3.setCreateTime(new Date());
  48.         article3.setUpdateTime(new Date());
  49.         article3.setViewCount(786);
  50.         articleRepository.save(article3);
  51.     }
  52.     @Test
  53.     public void findDistinctByTitleContainingOrContentContainingTest() throws Exception {
  54.         Pageable pageable = new PageRequest(0,20);
  55.         String title = "我爱罗琪";
  56.         String content = "花千树";
  57.         Page<Article> page = articleRepository.findDistinctByTitleContainingOrContentContaining(title, content, pageable);
  58.         System.out.println(page);
  59.         System.out.println("---start---");
  60.         for(Article article : page.getContent()) {
  61.             System.out.println(article.toString());
  62.         }
  63.         System.out.println("---end---");
  64.     }
  65. }
  运行 @Test 注解的方法 根据 title 和 content 内容查到一条数据   修改 title 和 content
String title = "蝶恋";
String content = "东风";
查到三条数据  

六、访问 http://localhost:9200/_plugin/head/

因为上一篇文章中,我们讲了装一个 head 插件,现在我们就能看到里面的数据了(多余的数据是之前测试的)

七、新建 Controller 类

ArticleController.java
  1. package com.liuyanzhao.chuyun.controller;
  2. import com.liuyanzhao.chuyun.domain.es.Article;
  3. import com.liuyanzhao.chuyun.repository.es.ArticleRepository;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.data.domain.Page;
  6. import org.springframework.data.domain.PageRequest;
  7. import org.springframework.data.domain.Pageable;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.RequestParam;
  10. import org.springframework.web.bind.annotation.RestController;
  11. import java.util.List;
  12. /**
  13.  * @author 言曌
  14.  * @date 2018/1/22 下午9:07
  15.  */
  16. @RestController
  17. @RequestMapping("/article")
  18. public class ArticleController {
  19.     @Autowired
  20.     private ArticleRepository articleRepository;
  21.     @RequestMapping("")
  22.     public List<Article> list(@RequestParam(value = "title", required = false) String title,
  23.                                 @RequestParam(value = "content", required = false) String content,
  24.                                 @RequestParam(value = "pageIndex", defaultValue = "0"int pageIndex,
  25.                                 @RequestParam(value = "pageSize", defaultValue = "10"int pageSize) {
  26.         Pageable pageable = new PageRequest(pageIndex, pageSize);
  27.         Page<Article> page = articleRepository.findDistinctByTitleContainingOrContentContaining(title, content, pageable);
  28.         return page.getContent();
  29.     }
  30. }
  因为之前在 测试类 里已经给 elasticsearch 添加了数据 所有现在可以在浏览器上访问: http://localhost:8080/chuyun/article?title=浪淘沙&content=伊人       本文地址:https://liuyanzhao.com/7170.html  
  • 微信
  • 交流学习,有偿服务
  • weinxin
  • 博客/Java交流群
  • 资源分享,问题解决,技术交流。群号:590480292
  • weinxin
avatar

发表评论

avatar 登录者:匿名
匿名评论,评论回复后会有邮件通知

  

已通过评论:4   待审核评论数:0
  1. avatar soul

    的撒旦

  2. avatar 永远的小信长

    it's ok 可以

  3. avatar sk2

    :cool: 厉害

  4. avatar 哦引力

    发现现在找个破解版的软解越来越难了