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();
}
相关推荐
罗政2 小时前
[附源码]超简洁个人博客网站搭建+SpringBoot+Vue前后端分离
vue.js·spring boot·后端
懒洋洋的华3692 小时前
消息队列-Kafka(概念篇)
分布式·中间件·kafka
Java小白笔记5 小时前
关于使用Mybatis-Plus 自动填充功能失效问题
spring boot·后端·mybatis
小哇6665 小时前
Spring Boot,在应用程序启动后执行某些 SQL 语句
数据库·spring boot·sql
happycao1236 小时前
kafka之路-01从零搭建环境到SpringBoot集成
kafka
happycao1237 小时前
kafka 配置自定义序列化方式
kafka
happycao1237 小时前
kafka Partition使用详解
kafka
luoluoal7 小时前
java项目之企业级工位管理系统源码(springboot)
java·开发语言·spring boot
蜜桃小阿雯8 小时前
JAVA开源项目 校园美食分享平台 计算机毕业设计
java·jvm·spring boot·spring cloud·intellij-idea·美食
计算机学姐9 小时前
基于SpringBoot+Vue的篮球馆会员信息管理系统
java·vue.js·spring boot·后端·mysql·spring·mybatis