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();
}
相关推荐
面向Google编程34 分钟前
从零学习Kafka:数据存储
后端·kafka
Jackeyzhe1 小时前
从零学习Kafka:数据存储
kafka
JH30732 小时前
SpringBoot 优雅处理金额格式化:拦截器+自定义注解方案
java·spring boot·spring
qq_12498707535 小时前
基于SSM的动物保护系统的设计与实现(源码+论文+部署+安装)
java·数据库·spring boot·毕业设计·ssm·计算机毕业设计
Coder_Boy_5 小时前
基于SpringAI的在线考试系统-考试系统开发流程案例
java·数据库·人工智能·spring boot·后端
2301_818732065 小时前
前端调用控制层接口,进不去,报错415,类型不匹配
java·spring boot·spring·tomcat·intellij-idea
汤姆yu9 小时前
基于springboot的尿毒症健康管理系统
java·spring boot·后端
暮色妖娆丶9 小时前
Spring 源码分析 单例 Bean 的创建过程
spring boot·后端·spring
biyezuopinvip10 小时前
基于Spring Boot的企业网盘的设计与实现(任务书)
java·spring boot·后端·vue·ssm·任务书·企业网盘的设计与实现
JavaGuide10 小时前
一款悄然崛起的国产规则引擎,让业务编排效率提升 10 倍!
java·spring boot