在kafka资料中有说明支持类同于rabbitmq的功能,通过查阅资料,kafka的通讯机制想必不用我写都知道,看到下图就能直接明白:
具体在project中操刀过程如下:
1.在发送和接收PROJECT中的MAVEN增加以下依赖包
2.在接收PROJECT里系统配置文件中增加以下配置信息,主要是为了consumer连接kafka server的topic及group
3.在接收prodject里增加以下组件,主要是为了接收信息,其中KafkaListener为监听topic为zll中信息
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
@Component
public class ListenerMsg {
@KafkaListener(topics = "zll")
public void processMessage(String content) {
// ...
System.out.println("recieve msg:" + content);
}
}
4.在发送的project里springboot配置文件中增加如下内容
5.在发送的project里增加以下component
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
@Component
public class SendMsg {
private Log log = LogFactory.getLog(SendMsg.class);
private final KafkaTemplate kafkaTemplate;
@Value("${spring.kafka.topic}")
private String topic;
@Autowired
public SendMsg(KafkaTemplate kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
for(int i=0;i<100;i++) {
this.SendMessge("hello "+i);
}
}
public void SendMessge(String msg) {
log.info("send send msg :"+msg);
this.kafkaTemplate.send("zll", msg);
}
}
7.先开启接收project在开发送project就能看到两边日志
发送方日志:
接收方日志: