繁体   English   中英

无法按需从 Kafka 读取记录

[英]Not able to read records form Kafka on demand

我正在使用生产者将数据推送到kafka队列。

然后我需要按需消费/读取数据,基本上我希望当一个rest api被触发时,我应该能够从kafka读取一条记录并返回。 我不希望消费者在数据到达队列时立即被调用,而是应该在我想要的时候被调用。

正常的读取方式是放入 while 循环,然后调用poll方法,然后在数据到达 Queue 时不断调用该方法。 但我想控制我何时阅读记录。

您仍然可以按需创建使用者并让它处理并返回单个记录。 像这样的东西:

...
   properties.setProperty(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "1");
   properties.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "test-group");
   KafkaConsumer consumer = new KafkaConsumer<>(properties);
   consumer.subscribe(Arrays.asList(topic));
   try {
        while (!timedOut) {
            ConsumerRecords records = consumer.poll(Duration.ofMillis(100));
            if (!records.isEmpty()) {
                // process record and return
            }
        }
        // error, no record found
    } catch (InterruptException e) {
    } finally {
        consumer.close();
    }
...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM