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();
}
相关推荐
vx_Biye_Design2 小时前
springboot高校选课系统82776-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·spring·课程设计·express
专业程序开发源4 小时前
SSM校园拍摄交流服务平台36936-计算机课程设计、毕业设计
java·spring boot·后端·python·elasticsearch·php·课程设计
AI人工智能+电脑小能手5 小时前
Java 企业级工具类全家桶-74-JSON序列化工具类
spring boot·jackson·jdk 17·objectmapper·java工具类·json序列化·dto互转
ZealSinger6 小时前
Boot4升级PostConstruct不跑了
java·spring boot·spring·升级迁移
专业程序开发源7 小时前
django新闻推荐系统70655-计算机课程设计、毕业设计
java·javascript·spring boot·后端·python·django·课程设计
vx_Biye_Design7 小时前
springboot一站式旅游管理平台81037-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·课程设计·express·旅游
vx_Biye_Design7 小时前
springboot宠物寄养服务预约与监管系统82684-计算机课程设计、毕业设计
java·vue.js·spring boot·elasticsearch·课程设计·express·宠物
程序员小杰@7 小时前
Spring Boot 常用注解分类速记
java·spring boot·后端
vx_Biye_Design7 小时前
springboot小学生英语学习APP62773-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·python·学习·课程设计
9624568 小时前
餐饮 SaaS 优惠券系统架构演进(三):优惠计算引擎——商品级计价、冲突策略与优惠分摊
java·数据库·spring boot