第六章
整合ES
实现接口
@Repository public interface DiscussPostRepository extends ElasticsearchRepository<DiscussPost, Integer> { }
public Page<DiscussPost> searchDiscussPost(String keyword, int current, int limit){ SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(QueryBuilders.multiMatchQuery(keyword, "title","content")) .withSort(SortBuilders.fieldSort("type").order(SortOrder.DESC)) .withSort(SortBuilders.fieldSort("score").order(SortOrder.DESC)) .withSort(SortBuilders.fieldSort("createTime").order(SortOrder.DESC)) .withPageable(PageRequest.of(current, limit)) .withHighlightFields( new HighlightBuilder.Field("title").preTags("<em>").postTags("</em>") ,new HighlightBuilder.Field("content").preTags("<em>").postTags("</em>") ).build(); return elasticTemplate.queryForPage(searchQuery, DiscussPost.class, new SearchResultMapper(){ @Override public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> aClass, Pageable pageable){ SearchHits hits = response.getHits(); if (hits.getTotalHits() <= 0){ return null; } List<DiscussPost> list = new ArrayList<>(); for (SearchHit hit:hits){ DiscussPost post = new DiscussPost(); String id = hit.getSourceAsMap().get("id").toString(); post.setId(Integer.valueOf(id)); String userId = hit.getSourceAsMap().get("userId").toString(); post.setUserId(Integer.valueOf(userId)); String title = hit.getSourceAsMap().get("title").toString(); post.setTitle(title); String content = hit.getSourceAsMap().get("content").toString(); post.setContent(content); String status = hit.getSourceAsMap().get("status").toString(); post.setStatus(Integer.valueOf(status)); String createTime = hit.getSourceAsMap().get("createTime").toString(); post.setCreateTime(new Date(Long.valueOf(createTime))); String commentCount = hit.getSourceAsMap().get("commentCount").toString(); post.setStatus(Integer.valueOf(commentCount)); //处理高亮显示的结果 HighlightField titleField = hit.getHighlightFields().get("title"); if (titleField != null){ post.setTitle(titleField.getFragments()[0].toString()); } HighlightField contentField = hit.getHighlightFields().get("content"); if (contentField != null){ post.setContent(contentField.getFragments()[0].toString()); } list.add(post); } return new AggregatedPageImpl(list, pageable, hits.getTotalHits(), response.getAggregations(), response.getScrollId(), hits.getMaxScore()); } }); }
触发发帖事件
//触发发帖事件 Event event = new Event().setTopic(TOPIC_PUBLISH).setUserId(user.getId()) .setEntityType(ENTITY_TYPE_POST).setEntityId(post.getId()); eventProducer.fireEvent(event);
消费事件
//消费发帖事件 @KafkaListener(topics = {TOPIC_PUBLISH}) public void handlePublishMessage(ConsumerRecord record){ if (record == null && record.value() == null){ logger.error("消息内容不能为空"); return; } Event event = JSONObject.parseObject(record.value().toString(), Event.class); if (event == null){ logger.error("消息格式错误" ); return; } DiscussPost post = discussPostService.findDiscussPostById(event.getEntityId()); elasticsearchService.saveDiscusspost(post); }