如何按需读取来自 Kafka 主题的消息 [英] How to read a message from Kafka topic on demand

查看:38
本文介绍了如何按需读取来自 Kafka 主题的消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何按需读取来自 Kafka 主题的消息.我有主题名称、offsetId、PartitionID,使用这三个参数,我如何从 Kafka 主题中检索特定消息.可以使用 Spring Kafka 吗?我正在使用 spring boot 2.2.4.RELEASE

How can I read a message from Kafka topic on demand. I have the topic name, offsetId, PartitionID, using these three params, how can i retrieve a specific message from Kafka Topic. Is it possible using Spring Kafka ? I am using spring boot 2.2.4.RELEASE

推荐答案

  • 创建消费者
  • 分配主题/分区
  • 寻求
  • 轮询一条记录
  • 关闭消费者
  • @SpringBootApplication
    public class So64759726Application {
    
        public static void main(String[] args) {
            SpringApplication.run(So64759726Application.class, args);
        }
    
        @Bean
        ApplicationRunner runner(ConsumerFactory<String, String> cf) {
            return args -> {
                try (Consumer<String, String> consumer = cf.createConsumer()) {
                    TopicPartition tp = new TopicPartition("so64759726", 0);
                    consumer.assign(Collections.singleton(tp));
                    consumer.seek(tp, 2);
                    ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(5));
                    System.out.println(records.iterator().next().value());
                }
            };
        }
    
    }
    

    application.properties

    application.properties

    spring.kafka.consumer.max-poll-records=1
    

    这篇关于如何按需读取来自 Kafka 主题的消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆