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();
}
相关推荐
NiNg_1_2342 小时前
SpringBoot整合SpringSecurity实现密码加密解密、登录认证退出功能
java·spring boot·后端
种树人202408192 小时前
如何在 Spring Boot 中启用定时任务
spring boot
苹果醋35 小时前
Java8->Java19的初步探索
java·运维·spring boot·mysql·nginx
Wx-bishekaifayuan5 小时前
django电商易购系统-计算机设计毕业源码61059
java·spring boot·spring·spring cloud·django·sqlite·guava
customer085 小时前
【开源免费】基于SpringBoot+Vue.JS周边产品销售网站(JAVA毕业设计)
java·vue.js·spring boot·后端·spring cloud·java-ee·开源
Yaml46 小时前
智能化健身房管理:Spring Boot与Vue的创新解决方案
前端·spring boot·后端·mysql·vue·健身房管理
LuckyLay6 小时前
Spring学习笔记_27——@EnableLoadTimeWeaving
java·spring boot·spring
Stringzhua7 小时前
【SpringCloud】Kafka消息中间件
spring·spring cloud·kafka
佳佳_7 小时前
Spring Boot 应用启动时打印配置类信息
spring boot·后端
程序媛小果8 小时前
基于java+SpringBoot+Vue的宠物咖啡馆平台设计与实现
java·vue.js·spring boot