SPRING BOOT+KAFKA 发送和接收message信息的实现

在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就能看到两边日志

发送方日志:

接收方日志:

 

    

 

 

  • 11
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值