SpringBoot集成kafka-获取生产者发送的消息(阻塞式和非阻塞式获取)


说明

CompletableFuture对象需要的SpringBoot版本为3.X.X以上,需要的kafka依赖版本为3.X.X以上,需要的jdk版本17以上。

1、阻塞式(等待式)获取生产者发送的消息

生产者:

java 复制代码
package com.power.producer;

import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.header.Headers;
import org.apache.kafka.common.header.internals.RecordHeaders;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.kafka.support.SendResult;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutionException;

@Component
public class EventProducer {

    @Resource
    private KafkaTemplate<String,String> kafkaTemplate;

    public void getResult(){
        //Integer partition, Long timestamp, K key, @Nullable V data
        CompletableFuture<SendResult<String, String>> result =
                kafkaTemplate.sendDefault(0, System.currentTimeMillis(), "k3", "hello-kafka");
        //怎么拿结果,通过ListenableFuture类拿结果
        try {
            //1、阻塞式等待拿结果
            SendResult<String, String> sendResult = result.get();

            if(null!=sendResult.getRecordMetadata()){
                //kafka服务器确认已经拿到了消息
                System.out.println("消息发送成功:"+sendResult.getRecordMetadata().toString());
            }
            System.out.println("producerRecord:"+sendResult.getProducerRecord());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

测试类:

java 复制代码
package com.power;

import com.power.producer.EventProducer;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;

@SpringBootTest
public class SpringBoot01KafkaBaseApplication {

    @Resource
    private EventProducer eventProducer;

    @Test
    void getResult(){
        eventProducer.getResult();
    }
}

测试结果:

java 复制代码
消息发送成功:default-topic-0@1
2024-08-22 22:18:51.344  INFO 8976 --- [ntainer#0-0-C-1] o.a.k.c.c.internals.ConsumerCoordinator  : [Consumer clientId=consumer-hello-group-1, groupId=hello-group] Adding newly assigned partitions: hello-topic-0
producerRecord:ProducerRecord(topic=default-topic, partition=0, headers=RecordHeaders(headers = [], isReadOnly = true), key=k3, value=hello-kafka, timestamp=1724336330821)

2、非阻塞式(非等待式)获取生产者发送的消息

生产者:

java 复制代码
package com.power.producer;

import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.header.Headers;
import org.apache.kafka.common.header.internals.RecordHeaders;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.kafka.support.SendResult;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@Component
public class EventProducer {

    @Resource
    private KafkaTemplate<String,String> kafkaTemplate;

    public void getResult2(){
        //Integer partition, Long timestamp, K key, @Nullable V data
        CompletableFuture<SendResult<String, String>> result =
                kafkaTemplate.sendDefault(0, System.currentTimeMillis(), "k3", "hello-kafka");
        //怎么拿结果,通过CompletableFuture类拿结果
        try {
            //2、非阻塞式等待拿结果
            result.thenAccept((sendResult)->{
                if(null!=sendResult.getRecordMetadata()){
                    //kafka服务器确认已经拿到了消息
                    System.out.println("消息发送成功:"+sendResult.getRecordMetadata().toString());
                }
                System.out.println("producerRecord:"+sendResult.getProducerRecord());
            }).exceptionally((e)->{
                e.printStackTrace();
                //做消息发送失败的处理
                System.out.println("消息发送失败");
                return null;
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

测试类:

java 复制代码
@Test
void getResult2(){
    eventProducer.getResult2();
}
相关推荐
学长毕设8 分钟前
基于SpringBoot的青少年编程学习平台系统-附源码
spring boot·学习·青少年编程
学长毕设5 小时前
基于SpringBoot的建筑材料管理系统-附源码
java·spring boot·后端
星光开发者6 小时前
基于springboot智慧草场牛羊管理系统-计算机毕设【课程设计】50360
vue.js·spring boot·后端·mysql·php·课程设计·express
weixin_BYSJ19877 小时前
电竞先锋网站---附源码02032
java·vue.js·spring boot·python·django·tomcat·php
她的男孩8 小时前
超时配置了自动驳回,任务状态却全变「已取消」:Forge Admin 流程超时终态与 Flowable ENTITY_DELETED
spring boot·低代码·工作流引擎
二宝哥9 小时前
02.springboot项目对接国内模型实现对话聊天
数据库·人工智能·spring boot
starzy199010 小时前
KafkaProducer 源码深度剖析:与 Broker 建立连接
大数据·kafka
学长毕设10 小时前
基于springboot的农资管理系统-附源码
java·spring boot·后端
Magicdata大数据12 小时前
AI辅助教学:调用大模型从教材中生成习题,方便学员练习
java·spring boot·大模型·知识图谱·neo4j·ai辅助教学
不识君12 小时前
esl-client 2.0.0 发布:Java 项目接入 FreeSWITCH,从引入到使用
spring boot·后端·开源