使用 KafkaTemplate 接收

本节介绍如何使用 KafkaTemplate 接收消息。

从 2.8 版本开始,该模板有四个 receive() 方法

ConsumerRecord<K, V> receive(String topic, int partition, long offset);

ConsumerRecord<K, V> receive(String topic, int partition, long offset, Duration pollTimeout);

ConsumerRecords<K, V> receive(Collection<TopicPartitionOffset> requested);

ConsumerRecords<K, V> receive(Collection<TopicPartitionOffset> requested, Duration pollTimeout);

如您所见,您需要知道要检索的记录的分区和偏移量;每次操作都会创建一个新的 Consumer(并关闭)。

对于最后两种方法,每条记录都是单独检索的,结果会组装成一个 ConsumerRecords 对象。在为请求创建 TopicPartitionOffsets 时,只支持正的绝对偏移量。

© . This site is unofficial and not affiliated with VMware.