1.准备依赖,在springboot父工程中
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
<version>${spring.kafka.version}</version>
</dependency>
2.在子工程生成者中调用kafkatemplate的send方法把内容发送到主题
@Autowired
private KafkaTemplate<String,String> kafkaTemplate;
kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC, JSON.toJSONString(searchArticleVo));
3.在子工程消费者中写一个监听类监听生产者发的内容通过@KafkaListener(topics = ArticleConstants.ARTICLE_ES_SYNC_TOPIC)
package com.heima.search.listener;
import com.alibaba.fastjson.JSON;
import com.heima.common.constants.ArticleConstants;
import com.heima.model.serch.vos.SearchArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Component
@Slf4j
public class articleListener {
@Autowired
private RestHighLevelClient restHighLevelClient;
/**
* 接收kafka发送的数据,创建索引
* @param msg
*/
@KafkaListener(topics = ArticleConstants.ARTICLE_ES_SYNC_TOPIC)
public void Listener(String msg){
if (StringUtils.isNotBlank(msg)) {
log.info("SyncArticleListener,message={}",msg);
SearchArticleVo searchArticleVo = JSON.parseObject(msg, SearchArticleVo.class);
// 创建索引请求指定索引名称为"app_info_article"
IndexRequest indexRequest = new IndexRequest("app_info_article");
//设置文档ID为searchArticleVo对象的ID属性值
indexRequest.id(searchArticleVo.getId().toString());
// 设置文档源,将msg作为JSON格式的文档源
indexRequest.source(msg, XContentType.JSON);
try {
// 执行批量请求,使用默认的请求选项
restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
} catch (IOException e) {
log.error("sync es error={}",e);
e.printStackTrace();
}
}
}
}