如何 运行 bin/kafka-console-consumer.sh 在 Spring 启动

How to run bin/kafka-console-consumer.sh in Spring boot

您好,我想查看主题中的所有消息,我可以通过 运行

在控制台中完成
bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test  --from-beginning

我有 Spring-kafka 2.6 依赖,希望得到帮助谢谢

答案是定义bean

    private final KafkaConsumer<String,String> consumer;

然后在你的方法中

   try {
            consumer.subscribe(Collections.singletonList(topic));
            ConsumerRecords<String, String> records = consumer.poll(TIMEOUT);
    } finally {
            consumer.unsubscribe();
       
    }