SpringBoot集成Kafka

SpringBoot整合Kafka:从入门到实践
本文详细介绍了如何使用SpringBoot集成Kafka,包括导入依赖、启动Kafka服务、创建生产者和消费者,以及点对点、发布订阅模式的消息传递。同时展示了消息发送的回调方法和事务处理,提供了完整的代码示例。

啦啦啦啦啦,富贵同学又开始开坑了,出了个免费的专栏,主要给大家从0基础开始用springBoot集成第三方的插件或者功能,如果这篇专栏能帮到你,一定不要忘了点一个赞哦!!欢迎大家收藏分享

在这里插入图片描述

第一步,导入jar包

        <dependency>
            <groupId>org.springframework.kafka</groupId>
            <artifactId>spring-kafka</artifactId>
        </dependency>

第二步,服务器上启动kafka

如果不知道怎么安装,启动请查看博主的文章
https://blog.youkuaiyun.com/csdnerM/article/details/121851493
配置文件连接kafka

spring.kafka.bootstrap-servers=ip:端口
spring.kafka.consumer.group-id=consumer-group

点对点消费

编写生产类

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author MaSiyi
 * @version 1.0.0 2021/12/10
 * @since JDK 1.8.0
 */
@RestController
public class KafkaProducer {

    @Autowired
    private KafkaTemplate<String, Object> kafkaTemplate;

    /** 发送消息
     * @Param:
     * @return:
     * @Author: MaSiyi
     * @Date: 2021/12/10
     */
    @GetMapping("/kafka/normal/{topic}/{message}")
    public void sendMessage1(@PathVariable("topic") String topic, @PathVariable("message") String normalMessage) {
        kafkaTemplate.send(topic, normalMessage);
    }

}

编写消费者

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;

/**
 * @author MaSiyi
 * @version 1.0.0 2021/12/10
 * @since JDK 1.8.0
 */
@Service
public class KafkaConsumer {

    /** 消费监听
     * @Param: [record]
     * @return: void
     * @Author: MaSiyi
     * @Date: 2021/12/10
     */
    @KafkaListener(topics = {"topictest1"})
    public void message1(ConsumerRecord<?, ?> record){
        // 消费的哪个topic、partition的消息,打印出消息内容
        System.out.println("点对点消费1:"+record.topic()+"-"+record.partition()+"-"+record.value());
    }

}

测试
在这里插入图片描述
在这里插入图片描述

如果有两个方法

   /** 点对点消费
     * @Param: [record]
     * @return: void
     * @Author: MaSiyi
     * @Date: 2021/12/10
     */
    @KafkaListener(topics = {"topictest1"})
    public void message1(ConsumerRecord<?, ?> record){
        // 消费的哪个topic、partition的消息,打印出消息内容
        System.out.println("点对点消费1:"+record.topic()+"-"+record.partition()+"-"+record.value());
    }
    /** 点对点消费
     * @Param: [record]
     * @return: void
     * @Author: MaSiyi
     * @Date: 2021/12/10
     */
    @KafkaListener(topics = {"topictest1"})
    public void message(ConsumerRecord<?, ?> record){
        // 消费的哪个topic、partition的消息,打印出消息内容
        System.out.println("点对点消费2:"+record.topic()+"-"+record.partition()+"-"+record.value());
    }

则只会消费一个
在这里插入图片描述

发布订阅模式

生产者是同一个,消费者如下

 /** 发布订阅模式
     * @Param: [record]
     * @return: void
     * @Author: MaSiyi
     * @Date: 2021/12/10
     */
    @KafkaListener(topics = {"topictest2"},groupId = "1")
    public void message2(ConsumerRecord<?, ?> record){
        // 消费的哪个topic、partition的消息,打印出消息内容
        System.out.println("发布订阅模式1:"+record.topic()+"-"+record.partition()+"-"+record.value());
    }
    /** 发布订阅模式
     * @Param: [record]
     * @return: void
     * @Author: MaSiyi
     * @Date: 2021/12/10
     */
    @KafkaListener(topics = {"topictest2"},groupId = "2")
    public void message3(ConsumerRecord<?, ?> record){
        // 消费的哪个topic、partition的消息,打印出消息内容
        System.out.println("发布订阅模式2:"+record.topic()+"-"+record.partition()+"-"+record.value());
    }

测试
在这里插入图片描述
在这里插入图片描述

方法回调

生产者

	@GetMapping("/kafka/callbackOne/{message}")
    public void sendMessage2(@PathVariable("message") String callbackMessage) {
        kafkaTemplate.send("topictest3", callbackMessage).addCallback(success -> {
            // 消息发送到的topic
            String topic = success.getRecordMetadata().topic();
            // 消息发送到的分区
            int partition = success.getRecordMetadata().partition();
            // 消息在分区内的offset
            long offset = success.getRecordMetadata().offset();
            System.out.println("发送消息成功:" + topic + "-" + partition + "-" + offset);
        }, failure -> {
            System.out.println("发送消息失败:" + failure.getMessage());
        });
    }
    @GetMapping("/kafka/callbackTwo/{message}")
    public void sendMessage3(@PathVariable("message") String callbackMessage) {
        kafkaTemplate.send("topictest3", callbackMessage).addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
            @Override
            public void onFailure(Throwable ex) {
                System.out.println("发送消息失败:"+ex.getMessage());
            }

            @Override
            public void onSuccess(SendResult<String, Object> result) {
                System.out.println("发送消息成功:" + result.getRecordMetadata().topic() + "-"
                        + result.getRecordMetadata().partition() + "-" + result.getRecordMetadata().offset());
            }
        });
    }

消费者

/** 消息回调
     * @Param: [record]
     * @return: void
     * @Author: MaSiyi
     * @Date: 2021/12/10
     */
    @KafkaListener(topics = {"topictest3"})
    public void message4(ConsumerRecord<?, ?> record){
        // 消费的哪个topic、partition的消息,打印出消息内容
        System.out.println("回调方法:"+record.topic()+"-"+record.partition()+"-"+record.value());
    }

测试
在这里插入图片描述
在这里插入图片描述

事物提交

有异常不发送

    @GetMapping("/kafka/transaction1")
    public void sendMessage4(){
        // 声明事务:后面报错消息不会发出去
        kafkaTemplate.executeInTransaction(operations -> {
            operations.send("topictest4","test executeInTransaction");
            throw new RuntimeException("fail");
        });
    }

接收者

    /** 事物
     * @Param: [record]
     * @return: void
     * @Author: MaSiyi
     * @Date: 2021/12/10
     */
    @KafkaListener(topics = {"topictest4"})
    public void message5(ConsumerRecord<?, ?> record){
        // 消费的哪个topic、partition的消息,打印出消息内容
        System.out.println("回调方法:"+record.topic()+"-"+record.partition()+"-"+record.value());
    }

测试
在这里插入图片描述

没有发送
在这里插入图片描述

有异常发送

    @GetMapping("/kafka/transaction2")
    public void sendMessage5(){
        // 不声明事务:后面报错但前面消息已经发送成功了
        kafkaTemplate.send("topictest4","test executeInTransaction");
        System.out.println("发送消息");
        throw new RuntimeException("fail");
    }

测试
在这里插入图片描述
已发送
在这里插入图片描述

好了,就是这么的简单,完整代码请移至SpringBoot+Kafka 查看
在这里插入图片描述

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

掉头发的王富贵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值