栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

仿牛客社区项目笔记-分布式搜索引擎(引入Elasticsearch)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

仿牛客社区项目笔记-分布式搜索引擎(引入Elasticsearch)

仿牛客社区项目笔记-分布式搜索引擎(引入Elasticsearch)
  • 1. 分布式搜索引擎
    • 1.1 引入Elasticsearch
    • 1.2 Spring 整合 Elasticsearch
    • 1.3 开发社区搜索功能
      • 1.3.1 搜索功能
      • 1.3.2 更新Elasticsearch 服务器中的帖子

1. 分布式搜索引擎

分为引入Elasticsearch,Spring 整合 Elasticsearch,开发社区搜索功能。

1.1 引入Elasticsearch

Elasticsearch简介:

  1. 在 www.elastic.co 下载 Elasticsearch 6.4.3 版本,与 SpringBoot 版本匹配。7.x 版本不兼容。(7.x版本将类型去掉)
  2. 解压缩到磁盘,将 config 中的 elasticsearch.yml 文件中的 cluster.name 改为项目名,将 path.data, path.logs 路径改为磁盘路径。配置环境变量。
  3. 在 github 下载中文分词包 ik,解压到 plugins 文件夹下。
  4. 在 bin 文件夹下点击 elasticsearch.bat 使其运行,才能在postman客户端下进行命令行操作。
1.2 Spring 整合 Elasticsearch
  1. 在pom.xml 文件中添加 spring-boot-starter-data-elasticsearch 依赖。
  2. 在 application.properties 中设置配置。
  3. Elasticsearch 和 Redis 底层均依赖于 netty,存在冲突。在CommunityApplication 做系统配置修改解决冲突。
  4. 对 DiscussPost 实体类加注解,使 Elasticsearch 能够识别。在 Dao 层加入 DiscussPostRepository 接口继承于 ElasticsearchRepository ,即可直接调用增删改查方法。
  5. 在 ElasticsearchTests 测试类将帖子插入到 Elasticsearch 服务器中并进行简单查询。
1.3 开发社区搜索功能 1.3.1 搜索功能
  1. 在搜索框搜索关键字,映射到 SearchController 层的 /search。调用 elasticsearchService.searchDiscussPost 方法,传入关键词和分页信息。
  2. searchDiscussPost 方法构造一个 searchQuery 来实现标题和内容的多匹配查询,同时根据置顶等条件设置倒序。然后调用 elasticTemplate.queryForPage 的方法来进行查询,并且将匹配到的字段进行标红。然后将命中的帖子列表返回。
  3. 然后根据帖子列表聚合数据,将每个帖子的用户和点赞数量也放入其中。设置分页信息。
  4. 返回 /site/search。
1.3.2 更新Elasticsearch 服务器中的帖子

发布帖子,增加评论时要将帖子异步提交到 Elasticsearch 服务器。利用kafka实现。

  1. 在 DiscussPostController 层的 /add 映射下,触发发帖事件,构造 Topic 为 TOPIC_PUBLISH 的 Event,需要设置userId,EntityType,EntityId。然后使用 eventProducer.fireEvent 开始生产。见 帖子模块(核心)1.2小节。
  2. 在 CommentController 层的 /add/{discussPostId} 映射下,判断一下评论的是不是帖子,如果是则触发发帖事件。同上。见 帖子模块(核心)1.5小节。
  3. 在 EventConsumer 中构建消费发帖事件,监听的 Topic 为 TOPIC_PUBLISH。判断消息是否为空,不为空将消息转为 Event,然后根据 Event 的 EntityId 获取到帖子,然后调用 discussRepository.save 方法将帖子插入到Elasticsearch 服务器中。
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/870934.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号